新規にUWPのプロジェクトを作成し、ボタンをはっ付けてクリックイベントを用意しとく。このボタンをクリックするとHTTP通信して受信したデータをデバック出力に出力するようにする。
MainPage.xaml.csにusingを追加しておく。
using Windows.Web.Http;
クリックイベントをこんな感じにする。クリックイベントのメソッドには、asyncを付けるのをわすれないように。あと、例外処理を適当なので実際にはいい感じにしてくれ。
private async void button_Click(object sender, RoutedEventArgs e)
{
try
{
Uri uri = new Uri("http://www.nifty.com");
using (var httpClient = new HttpClient())
{
using (var res = await httpClient.GetAsync(uri))
{
if (res.IsSuccessStatusCode)
{
var text = await res.Content.ReadAsStringAsync();
Debug.WriteLine(text);
}
}
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
ついでなんで、オレオレ証明書のサーバに接続できるようにする。
次のusingを追加する。
using Windows.Web.Http.Filters;
using Windows.Security.Cryptography.Certificates;
クリックイベントはこんな感じだ。あと、オレオレ証明書のサーバーはデバック用にLAN上に用意するのが普通なんで、Package.appxmanifesでプライベートネットワーク(クライアントとサーバー)にチェックを入れておく。
private async void button_Click(object sender, RoutedEventArgs e)
{
try
{
Uri uri = new Uri("https://192.168.0.1");
var filter = new HttpBaseProtocolFilter();
filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Expired);
filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);
filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName);
using (var httpClient = new HttpClient(filter))
{
using (var res = await httpClient.GetAsync(uri))
{
if (res.IsSuccessStatusCode)
{
var text = await res.Content.ReadAsStringAsync();
Debug.WriteLine(text);
}
}
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
コメント