900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > php post 400 post数据时报错:远程服务器返回错误: (400) 错误的请求。

php post 400 post数据时报错:远程服务器返回错误: (400) 错误的请求。

时间:2018-09-20 15:27:02

相关推荐

php post 400 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())):.WebException: 远程服务器返回错误: (400) 错误的请求。 在 .HttpWebRequest.GetResponse() 。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。