码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-12-22 17:23:55      阅读:617      评论:0      收藏:0      [点我收藏+]

标签:res   toe   exce   data   end   ring   ade   value   protect   

网上查了多种方法,有不少说法,报400说是传的数据格式不对,最后的结论确实是数据格式不对。

Content_Type为:application/json,配的数据格式有些麻烦,特别数多层,单层还好。
例如,我本传的数据是这个的json:

{
  "key1": {
    "key11": "value11",
    "key12": "value12"
  },
  "key2": "value2"
}

这时候,postData应该为:{"client":"{\"machineId\":\"1040\",\"value\":\"1\"}","userId":"5","temp":"91D3EB4181237881A227DF29B304738D"}

c#里赋值写法为:

string _postData = "{\"client\":\"{\\\"machineId\\\":\\\"1040\\\",\\\"value\\\":\\\"1\\\"}\",\"userId\":\"5\",\"temp\":\"91D3EB4181237881A227DF29B304738D\"}";

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() 。

 

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

标签:res   toe   exce   data   end   ring   ade   value   protect   

原文地址:https://www.cnblogs.com/Iven-zhang/p/10161648.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!