「[[マイクロソフト系技術情報 Wiki>http://techinfoofmicrosofttech.osscons.jp/]]」は、「[[Open棟梁Project>https://github.com/OpenTouryoProject/]]」,「[[OSSコンソーシアム .NET開発基盤部会>https://www.osscons.jp/dotNetDevelopmentInfrastructure/]]」によって運営されています。 -[[戻る>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); ***GET [#hff0cdc1] GETについては、[[上記コード>#vaee7008]]の -Method = HttpMethod.Post ---> Method = HttpMethod.Get に変更。 -httpRequestMessage.Content プロパティを設定しない。 でイケる。と思う。 ***JSON [#j80b5c5e] JSONのPOSTについては、 >[[上記コード>#vaee7008]]のhttpRequestMessage.Content プロパティに[[JSON文字列を指定する>JSONのparseを色々試してみた。]]。 でイケる。と思う。 ちょっとコツがあった(以下のような感じ)。 httpRequestMessage.Content = new StringContent( JsonConvert.SerializeObject(new { language = "ja" }), Encoding.UTF8, "application/json"); **ポイント [#l0c18008] ***Make your HttpClient static. [#vf2acf0c] -以下の問題があるので、HttpClientは基本的に、 --staticで使用する。 --都度、instance化しないこと(適切にdisposeしてもダメ)。 -参考 --開発者を苦しめる.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/ ***認証プロキシを通す場合 [#o5d5fc6b] 以下が参考になる。 -HttpClient で 認証プロキシ サーバーを使用するには – 荒井省三のBlog~ https://blogs.msdn.microsoft.com/shozoa/2014/09/02/httpclient/ **参考 [#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 *WebClientクラス [#c6b27e18] .NETでHTTPリクエストを処理するための最古のAPI。 **サンプル [#l4163c6f] 以下が参考になる。 -DOBON.NET > .NET Tips: C#, VB.NET --WebClientクラスでWebページを取得するには? - @IT~ http://www.atmarkit.co.jp/ait/articles/0505/20/news138.html --ファイルをダウンロードし保存する~ http://dobon.net/vb/dotnet/internet/downloadfile.html --ファイルをダウンロードし表示する~ http://dobon.net/vb/dotnet/internet/webclientopenread.html **参考 [#hd232f9a] -WebClient クラス (System.Net)~ https://msdn.microsoft.com/ja-jp/library/system.net.webclient.aspx *WebRequest, WebResponseクラス [#t3ae0017] SilverlightがSOAPサーバーと通信するケースが増えたため、追加されたAPI。 -WebClientとの違いは、 --WebRequest, WebResponseの2クラスに分割され、非同期対応がなされた。 --WebResponseを使用してRequestを送信し、CallbackでWebResponseを取得する。 -各クラスには以下の派生クラスがある。 --HttpWebRequest、FileWebRequest、FtpWebRequest --HttpWebResponse、FileWebResponse、FtpWebResponse **サンプル [#cc8b82cf] 以下が参考になる。 -DOBON.NET > .NET Tips: C#, VB.NET~ --WebRequest/WebResponseクラスでWebページを取得するには? - @IT~ http://www.atmarkit.co.jp/ait/articles/0506/10/news122.html --WebRequest、WebResponseクラスを使ってファイルをダウンロードし表示する~ http://dobon.net/vb/dotnet/internet/webrequest.html **参考 [#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 *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 + ', ' + responseData); }, error: function (responseData, textStatus, errorThrown) { alert(textStatus + ', ' + errorThrown.message); } }); }); ***GET [#o77cd2c8] 上記を、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 [#o10807ea] 以下は、Web Storageからkey, valueをJSONでPOSTする例。~ JSON文字列へのシリアライズ処理には[[JSON.stringify()>JSONのparseを色々試してみた。#e56c0f75]]を使用する // --------------------------------------------------------------- // 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); } }); } **参考 [#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/ -HttpClient詳解、或いは非同期の落とし穴について~ http://www.slideshare.net/neuecc/httpclient ---- Tags: [[:.NET開発]], [[:.NET Core]], [[:.NET Standard]], [[:ASP.NET]], [[:ASP.NET Web API]]