網上查了多種方法,有不少說法,報400說是傳的數據格式不對,最后的結論確實是數據格式不對。
Content_Type為:application/json,配的數據格式有些麻煩,特別數多層,單層還好。
例如,我本傳的數據是這個的json:
{
"key1": {
"key11": "value11",
"key12": "value12"
},
"key2": "value2"
}
這時候,postData應該為:{"key1": {\"key11\": \"value11\",\"key12\": \"value12\"},"key2": "value2"}
c#里賦值寫法為:
string _postData = "{\"key1\": \"{\\\"key11\\\": \\\"value11\\\",\\\"key12\\\": \\\"value12\\\"}\",\"key2\": \"value2\"}";
post的方法:
protected string PostUrl(string url, string postData)
{
try
{
HttpWebRequest webrequest = (HttpWebRequest)HttpWebRequest.Create(url);
webrequest.Method = "post";
webrequest.ContentType = "application/json;charset=utf-8";
byte[] postdatabyte = Encoding.UTF8.GetBytes(postData);
webrequest.ContentLength = postdatabyte.Length;
Stream stream;
stream = webrequest.GetRequestStream();
stream.Write(postdatabyte, 0, postdatabyte.Length);
stream.Close();
using (var httpWebResponse = webrequest.GetResponse())
using (StreamReader responseStream = new StreamReader(httpWebResponse.GetResponseStream()))
{
String ret = responseStream.ReadToEnd();
string result = ret.ToString();
return result;
}
}
catch (Exception ex)
{
HttpContext.Current.Response.Write(ex);
return "";
}
}
如果posData的格式寫錯,運行后報錯(using (var httpWebResponse = webrequest.GetResponse())):System.Net.WebException: 遠程服務器返回錯誤: (400) 錯誤的請求。 在 System.Net.HttpWebRequest.GetResponse() 。

