Open棟梁Project - マイクロソフト系技術情報 Wiki
.NETクライアントからHTTPリクエストを送る場合、
従来は、
使用していたが、こちらは設計が古いもよう。
新しくは、.NET Framework 4.5 では BCL 入りした
System.Net.Http.dllのHttpClientクラスを使用する。
なお、JavaScriptからは、jQuery.ajax()を使用する。
.NET Framework 4.5 で BCL 入りした、高機能で使い勝手がいいAPI。
以下の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);
.NETでHTTPリクエストを処理するための最古のAPI。
SilverlightがSOAPサーバーと通信するケースが増えたため、追加されたAPI。
HTTPリクエストを使用してデータを取得するajax の最も低レベルな実装。
以下の様なメソッドも存在する。
以下のjQuery.ajaxによるPOSTのサンプル・スニペットを使用すれば色々なパターンを処理可能。
$('#btnTest').click(function () {
var token = fragment.access_token;
alert('token: ' + token);
$.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 + ', ' + JSON.stringify(responseData));
},
error: function (responseData, textStatus, errorThrown) {
alert(textStatus + ', ' + errorThrown.message);
}
});
});
Tags: :ASP.NET