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

***GET [#hff0cdc1]
GETについては、[[上記コード>#vaee7008]]の
-Method = HttpMethod.Post ---> Method = HttpMethod.Get に変更。
-httpRequestMessage.Content プロパティを設定しない。

でイケる。と思う。

***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。

**サンプル [#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 + ', ' + JSON.stringify(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 + ', ' + JSON.stringify(responseData));
         },
         error: function (responseData, textStatus, errorThrown) {
             alert(textStatus + ', ' + errorThrown.message);
         }
     });
 }

***JSON [#o10807ea]

***認証CookieをCROSで送信 [#l6bc1b72]
以下が参考になるが、

-CORSリクエストでクレデンシャル(≒クッキー)を必要とする場合の注意点 - Qiita~
http://qiita.com/kawaz/items/1e51c374b7a13c21b7e2

最近の[[OAuth]] 2.0 や [[OpenID Connect]]等では、"Implicit Grant"と呼ばれるWebAPI専用フローがあり、認証Cookieは使用しないで、~
Bearer TokenというものをHTTPヘッダに付与して認証・認可するのが一般的になってきている。CROSの認証などもコレによって行う。

**参考 [#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: [[:ASP.NET]]

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