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

目次

概要

.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);

GET

GETについては、上記コード

でイケる。と思う。

JSON

JSONのPOSTについては、

上記コードのhttpRequestMessage?.Content プロパティにJSON文字列を指定する

でイケる。と思う。

ポイント

Make your HttpClient? static.

認証プロキシを通す場合

以下が参考になる。

参考

WebClient?クラス

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

サンプル

以下が参考になる。

参考

WebRequest?, WebResponse?クラス

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

サンプル

以下が参考になる。

参考

jQuery.ajax()

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

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

サンプル

POST

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

$('#btnTest').click(function () {
    $.ajax({
        type: 'post',
        url: 'http://・・・',
        crossDomain: true,
        contentType: 'application/x-www-form-urlencoded',
        headers: {
            'Authorization': 'Bearer ' + token
        },
        data: {
            client_id: '・・・',
            client_secret: '・・・',
        },
        xhrFields: {
            withCredentials: true
        },
        success: function (responseData, textStatus, jqXHR) {
            alert(textStatus + ', ' + responseData);
        },
        error: function (responseData, textStatus, errorThrown) {
            alert(textStatus + ', ' + errorThrown.message);
        }
    });
});

GET

上記を、GETもイケるよう、改造した。

urlに'get'を、postdataにはnullを指定する。

function CallOAuthAPI(url, httpMethod, postdata) {
    $.ajax({
        type: httpMethod,
        url: url,
        crossDomain: true,
        headers: {
            'Authorization': 'Bearer ' + token
        },
        data: postdata,
        xhrFields: {
            withCredentials: true
        },
        success: function (responseData, textStatus, jqXHR) {
            alert(textStatus + ', ' + responseData);
        },
        error: function (responseData, textStatus, errorThrown) {
            alert(textStatus + ', ' + errorThrown.message);
        }
    });
}

JSON

以下は、Web Storageからkey, valueをJSONでPOSTする例。
JSON文字列へのシリアライズ処理にはJSON.stringify()を使用する

// ---------------------------------------------------------------
// Web Storageからkey, valueをJSONでPOSTする。
// ---------------------------------------------------------------
// 引数    url : POST先のURL
// 戻り値  -
// ---------------------------------------------------------------
function PostJsonWebStorage(url) {
    // Web Storageのすべての情報の取得
    var jsonArray = new Array();

    for (var i = 0; i < storage.length; i++) {
        var _key = storage.key(i);

        // Web Storageのキーと値を表示
        var jsonBean = {
            key: _key,
            value: storage.getItem(_key)
        };

        jsonArray.push(jsonBean);
    }

    // <p id="url"></p> に表示
    if (document.getElementById("url") != null) {
        $("#url").text(url);
    }
    // <p id="request"></p> に表示
    if (document.getElementById("request") != null) {
        $("#request").text("request:" + JSON.stringify(jsonArray).toString());
    }

    CallService("POST", url, JSON.stringify(jsonArray), "application/json; charset=utf-8", "JSON", false);
}

// ---------------------------------------------------------------
// ajax
// ---------------------------------------------------------------
// 引数
//         Type : GET or POST or PUT or DELETE verb
//         Url : Location of the service
//         Data : Data sent to server
//         ContentType : Content type sent to server
//         DataType : Expected data format from server
//         ProcessData : True or False
// 戻り値  -
// ---------------------------------------------------------------
function CallService(Type, Url, Data, ContentType, DataType, ProcessData) {
    $.ajax({
        type: Type,
        url: Url,
        data: Data,
        cache: false,
        contentType: ContentType,
        dataType: DataType,
        processdata: ProcessData,
        success: function (data) {
            // On Successfull service call
            ServiceSucceeded(data);
        },
        error: function (data) {
            // When Service call fails
            ServiceFailed(data);
        }
    });
}

参考

参考


Tags: :.NET開発, :.NET Core, :ASP.NET, :ASP.NET Web API


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