HTTP リクエスト・ライブラリ(「rq.csx」ファイル)
#r "System.Net.dll"
#r "System.Net.Http.dll"
System.Net.Http.HttpClient MakeHttpClient(
string strProxyUrl = null,
string strProxyId = null,
string strProxyPw = null )
{
var proxy = new System.Net.WebProxy( strProxyUrl );
proxy.Credentials = new System.Net.NetworkCredential( strProxyId, strProxyPw );
var handler = new System.Net.Http.HttpClientHandler();
handler.Proxy = proxy;
handler.UseProxy = (strProxyUrl != null);
return new System.Net.Http.HttpClient( handler );
}
delegate void HttpResProc( System.Net.Http.HttpResponseMessage res );
bool ReqHttp(
System.Net.Http.HttpClient rq,
System.Net.Http.HttpMethod method,
string strUrl,
HttpResProc fnCallback,
System.Net.Http.HttpContent content = null,
System.Net.Http.Headers.AuthenticationHeaderValue auth = null )
{
bool bResult;
using( var m = new System.Net.Http.HttpRequestMessage(method, strUrl) )
{
if( auth != null )
{
m.Headers.Authorization = auth;
}
if( content != null )
{
m.Content = content;
}
using( var task = rq.SendAsync(m) )
{
task.Wait();
bResult = (task.Result.StatusCode == System.Net.HttpStatusCode.OK);
if( bResult )
{
fnCallback( task.Result );
}
}
}
return bResult;
}
HTTP リクエスト・ライブラリの使用サンプル(「example-rq.csx」ファイル)
#r "System.Net.dll"
#r "System.Net.Http.dll"
#load "rq.csx"
using System;
using System.Net.Http;
var c = MakeHttpClient();
ReqHttp( c, HttpMethod.Get, "https://www.bing.com/", (res) =>
{
Console.WriteLine( "リクエスト成功" );
// 以下のコードを有効にすると Web ページの内容(HTML)を出力する
// Console.WriteLine( res.Content.ReadAsStringAsync().Result );
} );