Skip to content

Instantly share code, notes, and snippets.

@nissuk
Created October 7, 2011 15:16
Show Gist options
  • Save nissuk/1270494 to your computer and use it in GitHub Desktop.
Save nissuk/1270494 to your computer and use it in GitHub Desktop.
C#: HTTP POSTする単純な例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
namespace Example
{
class Program
{
/// <summary>
/// HTTP POSTする単純な例です。
/// </summary>
/// <param name="url">POSTする対象のURL</param>
/// <param name="parameters">POSTするパラメータ</param>
/// <returns>POSTに対するレスポンス</returns>
static WebResponse HttpPost(string url, Dictionary<string, object> parameters)
{
// Dictionaryをクエリ文字列のbyte配列に変換します。
var body = string.Join("&", parameters.Select(pair => {
return string.Format("{0}={1}",
Uri.EscapeDataString(pair.Key),
Uri.EscapeDataString(pair.Value.ToString()));
}).ToArray());
var bodyBytes = Encoding.ASCII.GetBytes(body);
// リクエストを生成します。
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
using (var requestStream = request.GetRequestStream()) {
requestStream.Write(bodyBytes, 0, bodyBytes.Length);
}
return request.GetResponse();
}
static void Main(string[] args)
{
var url = "http://localhost/test/post.php"; // たとえば <?php var_dump($_POST) ?> など
var parameters = new Dictionary<string, object>() {
{ "foo", 1 },
{ "bar", 2 },
};
try {
var response = HttpPost(url, parameters);
using (var responseStream = response.GetResponseStream())
using (var reader = new StreamReader(responseStream)) {
Console.WriteLine(reader.ReadToEnd());
}
} catch (WebException e) {
Console.WriteLine(e.ToString());
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment