LoginSignup
55
65

More than 5 years have passed since last update.

C# HTTPクライアントまとめ

Last updated at Posted at 2016-12-04
クラス 名前空間 アセンブリ 説明
WebRequest System.Net System.dll 抽象クラス。CreateメソッドでURIに応じてHttpWebRequestやFtpWebRequestを返す
HttpWebRequest System.Net System.dll WebRequestを継承したクラス
WebClient System.Net System.dll HttpWebRequestを簡単に使えるようにしたラッパー
HttpClient System.Net.Http System.Net.Http.dll .NET 4.5から。async/await対応
RestClient
RestRequest
RestSharp RestSharp.dll サードパーティ製。内部でHttpWebRequestを使っている。JSON, XMLのシリアライズ・デシリアライズ機能を備えている

HttpClientはリクエストの度にインスタンス生成・破棄をしてはいけない。メンバーに持って使いまわすことが推奨されている。インスタンス生成・破棄をするとその度にTCPコネクションが張られ、パフォーマンスを低下させる(開発者を苦しめる.NETのHttpClientのバグと紛らわしいドキュメント)。

しかしそれってWebClientHttpWebReqeustでは大丈夫なんだろうか?

WebClientでこのようなコードを書いてtcpdump -n port 80で見てみたところ、大丈夫だった。
ちゃんとTCPコネクションが使いまわされていた。

WebClient.cs
            using (WebClient client = new WebClient())
            {
                client.DownloadDataCompleted += (_, args) =>
                {
                    var headers = client.ResponseHeaders;
                    string s = "";
                    for (int i = 0; i < headers.Count; ++i)
                    {
                        string header = headers.GetKey(i);
                        foreach (string value in headers.GetValues(i))
                        {
                            s += string.Format("{0}: {1}\r\n", header, value);
                        }
                    }
                    txtHeaders.Text = s;
                    var bytes = args.Result;
                    var html = Encoding.UTF8.GetString(bytes);
                    txtResponse.Text = html;
                };
                client.DownloadDataAsync(new Uri(url));
            }
55
65
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
55
65