「マイクロソフト系技術情報 Wiki」は、「Open棟梁Project」,「OSSコンソーシアム .NET開発基盤部会」によって運営されています。
.NETクライアントからHTTPリクエストを送る場合、
従来は、
使用していたが、こちらは設計が古いもよう。
新しくは、.NET Framework 4.5 では BCL 入りした
System.Net.Http.dllのHttpClientクラスを使用する。
HttpClientクラスのハンドラ委任を構成可能。
下記の参考ページを見て。
.NET Framework 4.5 で BCL 入りした、高機能で使い勝手がいいAPI。
// HttpClient private static HttpClient _httpClient = new HttpClient();
// 通信用の変数
HttpRequestMessage httpRequestMessage = null;
HttpResponseMessage httpResponseMessage = null;
// HttpRequestMessage (Method & RequestUri)
httpRequestMessage = new HttpRequestMessage
{
Method = HttpMethod.Get,
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.Headers.ExpectContinue = false;
// HttpResponseMessage
httpResponseMessage = await _httpClient.SendAsync(httpRequestMessage);
response = await httpResponseMessage.Content.ReadAsStringAsync();
return (JObject)JsonConvert.DeserializeObject(response);
POST については、上記GETのコードの
// 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();
return JsonConvert.DeserializeObject<Dictionary<string, string>>(response);
JSONのPOSTについては、
上記コードのhttpRequestMessage?.Content プロパティにJSON文字列を指定する。
でイケる。と思う。
ちょっとコツがあった(以下のような感じ)。
httpRequestMessage.Content = new StringContent(
JsonConvert.SerializeObject(new
{
language = "ja"
}),
Encoding.UTF8, "application/json");
以下が参考になる。
認証プロキシを通す場合と同じだが、
という(非常に痛い)問題がある。
(WebProxy?.BypassProxyOnLocal?辺りの問題と切り分けが困難)
using System;
using System.Net.Http;
namespace ConsoleApp1
{
class Program
{
//private static readonly string proxyUrl = "http://127.0.0.1:8888";
//private static readonly string proxyAccount = "account";
//private static readonly string proxyPassword = "password";
private static readonly string targetUrl = "http://localhost/iisstart.htm";
static void Main(string[] args)
{
// HttpClientHandlerにProxy情報を設定する
HttpClientHandler ch = new HttpClientHandler();
//ch.Proxy = new WebProxy(proxyUrl);
//ch.Proxy.Credentials = new NetworkCredential(proxyAccount, proxyPassword);
//ch.UseProxy = true;
// HttpClientHandlerを用いてHttpClientを生成
HttpClient client = new HttpClient(ch);
try
{
// GETでレスポンスを取得
var task = client.GetStringAsync(targetUrl);
task.Wait();
Console.WriteLine(task.Result);
}
catch (Exception e)
{
Exception e2 = e.GetBaseException();
System.Console.WriteLine(e2.Message);
}
Console.ReadKey();
}
}
}
HttpClient?には、ハンドラ委任と言う概念がある
以下が参考になる。
SilverlightがSOAPサーバーと通信するケースが増えたため、追加されたAPI。
以下が参考になる。
Tags: :プログラミング, :通信技術, :.NET開発, :.NET Core, :ASP.NET, :ASP.NET Web API