Open棟梁Project - マイクロソフト系技術情報 Wiki

目次

概要

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

従来は、

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

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

なお、JavaScriptからは、jQuery.ajax()を使用する。

HttpClient?クラス

.NET Framework 4.5 で BCL 入りした、高機能で使い勝手がいいAPI。

サンプル

POST

以下のHttpClient?によるPOSTのサンプル・スニペットを使用すれば色々なパターンを処理可能。

// 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();
dic = JsonConvert.DeserializeObject<Dictionary<string, string>>(response);

JSON

参考

WebClient?クラス

.NETでHTTPリクエストを処理するための最古のAPI。

参考

WebRequest?, WebResponse?クラス

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

参考

jQuery.ajax()

HTTPリクエストを使用してデータを取得するajax の最も低レベルな実装。

以下の様なメソッドも存在する。

サンプル

POST

以下のjQuery.ajaxによるPOSTのサンプル・スニペットを使用すれば色々なパターンを処理可能。

JSON

参考

参考


Tags: :ASP.NET


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