post数据时报错:远程服务器返回错误: (400) 错误的请求。
网上查了多种方法,有不少说法,报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() 。
一份耕耘,一份收获,付出就有回报永不遭遇过失败,因我所碰到的都是暂时的挫折