マイクロソフト系技術情報 Wiki」は、「Open棟梁Project」,「OSSコンソーシアム .NET開発基盤部会」によって運営されています。

目次

概要

.NETクライアントからHTTPリクエストを送る場合、

従来は、

使用していたが、こちらは設計が古いもよう。

新しくは、.NET Framework 4.5 では BCL 入りした
System.Net.Http.dllのHttpClientクラスを使用する。

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 プロパティにJSON文字列を指定する

でイケる。と思う。

ちょっとコツがあった(以下のような感じ)。

httpRequestMessage.Content = new StringContent(
  JsonConvert.SerializeObject(new
  {
    language = "ja"
  }),
  Encoding.UTF8, "application/json");

ポイント

Make your HttpClient? static.

認証プロキシを通す場合

以下が参考になる。

デバッグ・プロシキを通す。

認証プロキシを通す場合と同じだが、

という(非常に痛い)問題がある。
WebProxy?.BypassProxyOnLocal?辺りの問題と切り分けが困難)

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();
        }
    }
}

その他のオプション

ハンドラ委任について。

HttpClient?には、ハンドラ委任と言う概念がある

参考

旧式のクラス

WebClient?クラス

サンプル

以下が参考になる。

参考

WebRequest?, WebResponse?クラス

SilverlightSOAPサーバーと通信するケースが増えたため、追加されたAPI。

サンプル

以下が参考になる。

参考

参考

JavaScript

引っ越しました。

jQuery.ajax()

, etc.

障害処理ポリシー

Exponential Backoff(指数バックオフ)

Polly(Retry, Circuit Breaker, Timeout, Bulkhead, Fallback)


Tags: :プログラミング, :通信技術, :.NET開発, :.NET Core, :ASP.NET, :ASP.NET Web API


トップ   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS