「マイクロソフト系技術情報 Wiki」は、「Open棟梁Project」,「OSSコンソーシアム .NET開発基盤部会」によって運営されています。 目次 †概要 †.NETクライアントからHTTPリクエストを送る場合、 従来は、 使用していたが、こちらは設計が古いもよう。 新しくは、.NET Framework 4.5 では BCL 入りした HttpClientFactory?クラス †概要 †
特徴 †HttpClientクラスのハンドラ委任を構成可能。
使い方 †基本的な使い方 †
使い方のパターン †
サンプル †下記の参考ページを見て。 参考 †Microsoft Docs †
その他 †
HttpClient?クラス †.NET Framework 4.5 で BCL 入りした、高機能で使い勝手がいいAPI。 サンプル †GET †// HttpClient private static HttpClient _httpClient = new HttpClient(); // 通信用の変数 HttpRequestMessage httpRequestMessage = null; HttpResponseMessage httpResponseMessage = null; // HttpRequestMessage (Method & RequestUri) httpRequestMessage = new HttpRequestMessage { Method = HttpMethod.Get, RequestUri = new Uri("http://localhost/・・・", }; // HttpRequestMessage (Headers & Content) httpRequestMessage.Headers.Authorization = new AuthenticationHeaderValue( "Basic", Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes( string.Format("{0}:{1}", "・・・", "・・・")))); httpRequestMessage.Headers.ExpectContinue = false; // HttpResponseMessage httpResponseMessage = await _httpClient.SendAsync(httpRequestMessage); response = await httpResponseMessage.Content.ReadAsStringAsync(); return (JObject)JsonConvert.DeserializeObject(response); POST †POST については、上記GETのコードの
// HttpClient private static HttpClient _httpClient = new HttpClient(); // HttpRequestMessage (Method & RequestUri) httpRequestMessage = new HttpRequestMessage { Method = HttpMethod.Post, RequestUri = new Uri("http://localhost/・・・", }; // HttpRequestMessage (Headers & Content) httpRequestMessage.Headers.Authorization = new AuthenticationHeaderValue( "Basic", Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes( string.Format("{0}:{1}", "・・・", "・・・")))); httpRequestMessage.Content = new FormUrlEncodedContent( new Dictionary<string, string> { { "grant_type", "authorization_code" }, { "code", code }, { "redirect_uri", System.Web.HttpUtility.HtmlEncode( "http://localhost/・・・") }, }); // HttpResponseMessage httpResponseMessage = await _httpClient.SendAsync(httpRequestMessage); response = await httpResponseMessage.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject<Dictionary<string, string>>(response); JSON †JSONのPOSTについては、
でイケる。と思う。 ちょっとコツがあった(以下のような感じ)。 httpRequestMessage.Content = new StringContent( JsonConvert.SerializeObject(new { language = "ja" }), Encoding.UTF8, "application/json"); ポイント †Make your HttpClient? static. †
認証プロキシを通す場合 †以下が参考になる。
デバッグ・プロシキを通す。 †認証プロキシを通す場合と同じだが、
using System; using System.Net.Http; namespace ConsoleApp1 { class Program { //private static readonly string proxyUrl = "http://127.0.0.1:8888"; //private static readonly string proxyAccount = "account"; //private static readonly string proxyPassword = "password"; private static readonly string targetUrl = "http://localhost/iisstart.htm"; static void Main(string[] args) { // HttpClientHandlerにProxy情報を設定する HttpClientHandler ch = new HttpClientHandler(); //ch.Proxy = new WebProxy(proxyUrl); //ch.Proxy.Credentials = new NetworkCredential(proxyAccount, proxyPassword); //ch.UseProxy = true; // HttpClientHandlerを用いてHttpClientを生成 HttpClient client = new HttpClient(ch); try { // GETでレスポンスを取得 var task = client.GetStringAsync(targetUrl); task.Wait(); Console.WriteLine(task.Result); } catch (Exception e) { Exception e2 = e.GetBaseException(); System.Console.WriteLine(e2.Message); } Console.ReadKey(); } } } 証明書の検証を無効化する。 †handlerに以下を加える。 handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; };
その他のオプション †...
ハンドラ委任について。 †HttpClient?には、ハンドラ委任と言う概念がある
参考 †
旧式のクラス †WebClient?クラス †
サンプル †以下が参考になる。
参考 †
WebRequest?, WebResponse?クラス †SilverlightがSOAPサーバーと通信するケースが増えたため、追加されたAPI。
サンプル †以下が参考になる。
参考 †
参考 †JavaScript †jQuery.ajax() †, etc. †障害処理ポリシー †Exponential Backoff(指数バックオフ) †Polly(Retry, Circuit Breaker, Timeout, Bulkhead, Fallback) †Tags: :プログラミング, :通信技術, :.NET開発, :.NET Core, :ASP.NET, :ASP.NET Web API |