HTTP POSTでデータを送信する方法|C#
C#でHTTP POSTを行う方法です。HttpClient
クラスのPostAsync()
メソッドを使用します。
C#で HTTP POST のサンプル
バイナリデータ(画像ファイル)と文字列をPOSTで送るサンプルです。送信先フォームは下記記事のものを想定しています。
HTTP POSTでファイルをアップロードして保存する|PHP
using System;
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\white.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");
await this._httpClient.PostAsync(uri, content);
}
}
}
送信データはMultipartFormDataContent
に詰めます。
サンプルでは受け取ってませんが、await this._httpClient.PostAsync();
の戻り値は非同期処理の結果になります。
呼び出し側
private void post() {
PostProcess process = PostProcess.GetInstance();
Uri uri = new Uri("http://localhost/post-form.php");
process.ExecuteHttpClient(uri);
}