Visual Studio community 2015 アカウントについて (学内専用)
- WebBrowser (基本)
- Form(自動操作)
- HttpClient ←今週
- REST & JSON
いままで、WebBrowser コントロールを利用して、 Webサイトを表示と操作プログラムを作りました。
今回は直接 http 通信に HttpClient クラスを使用 するプログラムを作ります。
HTTPとは
httpとは、代表的な通信プロトコルの一つで、インターネット上でWebサーバー(サイトの公開側)と、クライアント(ブラウザ:サイトを閲覧する側)が、相互に通信するために使用される仕組みです。
もっと言うと、Webサーバーとクライアント間で、HTML(Webページを作成するための言語)で記載された情報をやりとりするための仕組みです。
この「http」がないと、インターネット上のサイトを見ることができなくなるので、今や無くてはならない仕組みとなります。
HTTPコマンド
主なHTTPコマンドには次のようなものがあります。
| GET | 指定したページの取得を要求します。 |
| HEAD | メッセージヘッダを要求します。 |
| POST | フォームに入力したデータを送る |
| PUT | サーバーへデータをアップロードする |
| DELETE | サーバー上のデータを削除する |
HTTPコマンド応答メッセージ
主な応答メッセージには、次のようなものがあります。
| 200 | OK 正常に取得できた |
| 301 | 恒久的に移転した |
| 302 | 一時的に移転した |
| 403 | Forbidden アクセス拒否 |
| 404 | Not Found ファイルが見つからない |
HttpClient 通信プログラム
デザイン
- Form
- Form1
- TextBox
- textBox1 —
- Name : URL
- Text : http://wp-api.xyz
- textBox2 —
- Name : ProxyID
- Text : (your_proxy_id)
- textBox3 —
- Name : ProxyPW
- PasswordChar : *
- Text : (your_proxy_password)
- textBox4 —
- Name : HTTP_Results
- Multiline : True
- textBox1 —
- Button
- button1 —
- Name : Quit
- button2 —
- Name : Request
- button1 —
- CheckBox
- checkBox1 —
- Name : ProxyOn
- checkBox1 —
プログラム
HttpClient クラス
// for httpclient using System.Net.Http; using System.Net; using System.IO; using System.Runtime.Serialization; // using System.Runtime.Serialization.Json;
Quit ボタン
private void Quit_Click(object sender, EventArgs e)
{
Application.Exit();
}
Requestボタン
private async void Request_Click(object sender, EventArgs e)
{
if (ProxyOn.Checked)
{
// デフォルト プロキシ情報を取得して、資格情報を設定する
var proxy = WebRequest.DefaultWebProxy;
proxy.Credentials = new NetworkCredential(ProxyID.Text, ProxyPW.Text);
}
var client = new HttpClient();
string response = await client.GetStringAsync(URL.Text);
HTTP_Results.Text = response;
}
最終プログラム:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
// for httpclient
using System.Net.Http;
using System.Net;
using System.IO;
using System.Runtime.Serialization;
// using System.Runtime.Serialization.Json;
namespace web_get2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Quit_Click(object sender, EventArgs e)
{
Application.Exit();
}
private async void Request_Click(object sender, EventArgs e)
{
if (ProxyOn.Checked)
{
// デフォルト プロキシ情報を取得して、資格情報を設定する
var proxy = WebRequest.DefaultWebProxy;
proxy.Credentials = new NetworkCredential(ProxyID.Text, ProxyPW.Text);
}
var client = new HttpClient();
string response = await client.GetStringAsync(URL.Text);
HTTP_Results.Text = response;
}
}
}
実行結果


