これは、System.JSON名前空間で使用したコードのスニペットです。
public JsonValue Post(string address) {
JsonValue value = null;
try
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(address);
req.Method = "POST";
JsonObject postJson = new JsonObject();
foreach (KeyValuePair<string, string> val in this.FormParams)
postJson.Add(new KeyValuePair<string, JsonValue>(val.Key, new JsonPrimitive(val.Value)));
byte[] postData = new ASCIIEncoding().GetBytes(postJson.ToString());
req.ContentLength = postData.Length;
Stream dataStream = req.GetRequestStream();
dataStream.Write(postData, 0, postData.Length);
dataStream.Close();
using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
{
using (StreamReader reader = new StreamReader (resp.GetResponseStream ()))
{
value = JsonValue.Load(reader);
}
}
}
catch (Exception ex)
{
_lastError = ex.Message;
Log.Error(String.Format("Exception on JsonHandler::Post(action): {0}", ex.Message));
}
return value;
}
ここで、「action」はhttp://service-address.com/json/usersのようにアクセスするアドレスであり、
「this.FormParams」はポストデータを含むリストです。あらゆる種類のJSONオブジェクトを含むことができるJsonValueを返します。