※C#初心者なのでメモです
環境
- .NET Framework 3.5
4.0 からはDynamicJSONが使えるらしい
using追加
using System.IO;
using System.Net;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Web.Script.Serialization
データコントラクト定義
[DataContract]
public class RequestResult
{
[DataMember]
public string data1 { get; set; }
[DataMember]
public string data2 { get; set; }
[DataMember]
public string data3 { get; set; }
[DataMember]
public string data4 { get; set; }
}
実処理
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://example.com/api/hoge");
req.ContentType = "application/json";
req.Method = "POST";
using (var streamWriter = new StreamWriter(req.GetRequestStream()))
{
string jsonPayload = new JavaScriptSerializer().Serialize(new
{
hoge = "APIを",
piyo = "叩く際に渡す",
foo = "パラメータ"
});
streamWriter.Write(jsonPayload);
}
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
RequestResult result;
using (res)
{
using (var resStream = res.GetResponseStream())
{
var serializer = new DataContractJsonSerializer(typeof(RequestResult));
result = (RequestResult)serializer.ReadObject(resStream);
}
}
参考
- http://stackoverflow.com/questions/9145667/how-to-post-json-to-the-server
- https://msdn.microsoft.com/ja-jp/library/bb412179(v=vs.90).aspx
- https://msdn.microsoft.com/ja-jp/library/cc668800(v=vs.90).aspx
- https://msdn.microsoft.com/ja-jp/library/system.io.streamwriter(v=vs.110).aspx
- https://msdn.microsoft.com/ja-jp/library/system.net.httpwebresponse.getresponsestream(v=vs.110).aspx
- http://posnum.hatenablog.com/entry/2014/09/19/233255
- http://www.sonnagaya.com/entry/20140704/1404434783
- http://argius.hatenablog.jp/entry/20131113/1384352397