[[Open棟梁Project>http://opentouryo.osscons.jp/]] - [[マイクロソフト系技術情報 Wiki>http://techinfoofmicrosofttech.osscons.jp/]] -[[戻る>ASP.NET]] * 目次 [#sf757713] #contents *概要 [#e1a30627] .NETクライアントからHTTPリクエストを送る場合、 従来は、 -[[WebClientクラス>#c6b27e18]]や -[[WebRequest, WebResponseクラス>#t3ae0017]]を 使用していたが、こちらは設計が古いもよう。 新しくは、.NET Framework 4.5 では BCL 入りした~ System.Net.Http.dllの[[HttpClientクラス>#n074732e]]を使用する。 なお、JavaScriptからは、[[jQuery.ajax()>#m5888cea]]を使用する。 *HttpClientクラス [#n074732e] .NET Framework 4.5 で BCL 入りした、高機能で使い勝手がいいAPI。 **サンプル [#u8db561a] ***POST [#vaee7008] 以下の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 [#j80b5c5e] **参考 [#a1eb1525] -HttpClient クラス (System.Net.Http)~ https://msdn.microsoft.com/ja-jp/library/system.net.http.httpclient.aspx -.NET TIPS:HttpClientクラスでWebページを取得するには?[C#、VB] - @IT~ http://www.atmarkit.co.jp/ait/articles/1501/06/news086.html -Web API よりも HttpClient に注目したい - しばやん雑記~ http://blog.shibayan.jp/entry/20120822/1345563275 -開発者を苦しめる.NETのHttpClientのバグと紛らわしいドキュメント~ https://www.infoq.com/jp/news/2016/09/HttpClient --You're using HttpClient wrong and it is destabilizing your software | ASP.NET Monsters~ https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/ *WebClientクラス [#c6b27e18] .NETでHTTPリクエストを処理するための最古のAPI。 **参考 [#hd232f9a] -WebClient クラス (System.Net)~ https://msdn.microsoft.com/ja-jp/library/system.net.webclient.aspx -DOBON.NET > .NET Tips: C#, VB.NET --ファイルをダウンロードし保存する~ http://dobon.net/vb/dotnet/internet/downloadfile.html --ファイルをダウンロードし表示する~ http://dobon.net/vb/dotnet/internet/webclientopenread.html -.NET TIPS:WebClientクラスでWebページを取得するには? - @IT~ http://www.atmarkit.co.jp/ait/articles/0505/20/news138.html *WebRequest, WebResponseクラス [#t3ae0017] SilverlightがSOAPサーバーと通信するケースが増えたため、追加されたAPI。 -WebClientとの違いは、 --WebRequest, WebResponseの2クラスに分割され、非同期対応がなされた。 --WebResponseを使用してRequestを送信し、CallbackでWebResponseを取得する。 -各クラスには以下の派生クラスがある。 --HttpWebRequest、FileWebRequest、FtpWebRequest --HttpWebResponse、FileWebResponse、FtpWebResponse **参考 [#nccc74b8] -MSDN --WebRequest クラス (System.Net)~ https://msdn.microsoft.com/ja-jp/library/system.net.webrequest.aspx --WebResponse クラス (System.Net)~ https://msdn.microsoft.com/ja-jp/library/system.net.webresponse.aspx -DOBON.NET > .NET Tips: C#, VB.NET >~ WebRequest、WebResponseクラスを使ってファイルをダウンロードし表示する~ http://dobon.net/vb/dotnet/internet/webrequest.html -.NET TIPS:WebRequest/WebResponseクラスでWebページを取得するには? - @IT~ http://www.atmarkit.co.jp/ait/articles/0506/10/news122.html *jQuery.ajax() [#m5888cea] HTTPリクエストを使用してデータを取得するajax の最も低レベルな実装。 以下の様なメソッドも存在する。 -jQuery.get() -jQuery.post() **サンプル [#uaba5c4a] ***POST [#wbcbc8d7] 以下の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 + ', ' + JSON.stringify(responseData)); }, error: function (responseData, textStatus, errorThrown) { alert(textStatus + ', ' + errorThrown.message); } }); }); -上記を、GETもイケるよう、改造した。 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 + ', ' + JSON.stringify(responseData)); }, error: function (responseData, textStatus, errorThrown) { alert(textStatus + ', ' + errorThrown.message); } }); } ***JSON [#o10807ea] **参考 [#id231190] -jQuery API Documentation --jQuery.ajax()~ http://api.jquery.com/jquery.ajax/ --jQuery.get()~ http://api.jquery.com/jQuery.get/ --jQuery.post()~ http://api.jquery.com/jQuery.post/ -jQuery 日本語リファレンス --jQuery.ajax(options) - jQuery 日本語リファレンス~ http://semooh.jp/jquery/api/ajax/jQuery.ajax/options/ --jQuery.get( url, data, callback ) - jQuery 日本語リファレンス~ http://semooh.jp/jquery/api/ajax/jQuery.get/+url%2C+data%2C+callback+/ --jQuery.post( url, data, callback, type ) - ~ http://semooh.jp/jquery/api/ajax/jQuery.post/+url%2C+data%2+callback%2C+type+/ *参考 [#j377dfef] -ASP.NET Web API シンプルな文字列の POST について - miso_soup3 Blog~ http://miso-soup3.hateblo.jp/entry/2014/06/02/000603 -HttpClient で 認証プロキシ サーバーを使用するには – 荒井省三のBlog~ https://blogs.msdn.microsoft.com/shozoa/2014/09/02/httpclient/ ---- Tags: [[:ASP.NET]]