C#でHTTP通信を行う
HttpClient
クラスを使ってHTTP通信を行う方法です。
C#で HTTP POST を行う
PostAsync()
メソッドを使用します。
下のコードはバイナリデータ(画像ファイル)と文字列をPOSTで送るサンプルです。
using System;
using System.Diagnostics;
using System.IO;
using System.Net.Http;
namespace PostTest {
class PostProcess {
private static PostProcess _single = null;
private HttpClient _httpClient = null;
private PostProcess() {
_httpClient = new HttpClient();
}
~PostProcess() {
PostProcess.Dispose();
}
public static PostProcess GetInstance() {
if (_single == null) {
_single = new PostProcess();
}
return _single;
}
public static void Dispose() {
if (_single == null) {
return;
}
if (_single._httpClient == null) {
return;
}
_single._httpClient.Dispose();
_single = null;
}
public async void ExecuteHttpClient(Uri uri) {
string imagePath = @"C:\Users\Default\Pictures\sample.jpg";
MultipartFormDataContent content = new MultipartFormDataContent();
// バイナリデータ.
ByteArrayContent imageBytes = new ByteArrayContent(File.ReadAllBytes(imagePath));
content.Add(imageBytes, "imagefile", Path.GetFileName(imagePath));
// 文字列.
content.Add(new StringContent("E195335D5206A8CC06312DC2717CB514"), "checkkey");
content.Add(new StringContent("1"), "id");
content.Add(new StringContent("sandy"), "name");
var response = await _httpClient.PostAsync(uri, content);
Debug.WriteLine(response.StatusCode == System.Net.HttpStatusCode.OK);
}
}
}
送信データはMultipartFormDataContent
に詰めます。
呼び出し例
private void post() {
PostProcess.GetInstance().ExecuteHttpClient(new Uri("http://localhost:8080/post-api"));
}
C#で HTTP GET を行う
GetAsync()
メソッドを使用します。
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.Http;
using System.Web;
namespace GetTest {
class GetProcess {
private static GetProcess _single = null;
private HttpClient _httpClient = null;
private GetProcess() {
_httpClient = new HttpClient();
}
~GetProcess() {
GetProcess.Dispose();
}
public static GetProcess GetInstance() {
if (_single == null) {
_single = new GetProcess();
}
return _single;
}
public static void Dispose() {
if (_single == null) {
return;
}
if (_single._httpClient == null) {
_single = null;
return;
}
_single._httpClient.Dispose();
_single = null;
}
public async void ExecuteHttpClient(Uri uri, Dictionary<string, string> queries) {
System.Collections.Specialized.NameValueCollection query = HttpUtility.ParseQueryString("");
foreach (KeyValuePair<string, string> item in queries) {
query.Add(item.Key, item.Value);
}
UriBuilder builder = new UriBuilder(uri.AbsoluteUri);
builder.Query = query.ToString();
var response = await _httpClient.GetAsync(builder.Uri);
Debug.WriteLine(response.StatusCode == System.Net.HttpStatusCode.OK);
}
}
}
GETなので、パラメータはクエリ文字列で渡します。(実際のURLはbuilder.Uri.AbsoluteUri
で確認できます)
呼び出し例
private void getTest() {
Dictionary<string, string> queries = new Dictionary<string, string>();
queries.Add("arg", "abcdefg");
GetProcess.GetInstance().ExecuteHttpClient(new Uri("http://localhost:8080/get-api"), queries);
}