zoukankan      html  css  js  c++  java
  • 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() 。

  • 相关阅读:
    Intersection(计算几何)
    Happy Matt Friends(DP)
    Dire Wolf(区间DP)
    Black And White(DFS+剪枝)
    最大子矩阵
    Largest Rectangle in a Histogram (最大子矩阵)
    City Game(最大子矩阵)
    Zipper (DP)
    QQpet exploratory park(DP)
    C++程序设计(第4版)读书笔记_指针、数组与引用
  • 原文地址:https://www.cnblogs.com/raincedar/p/11017894.html
Copyright © 2011-2022 走看看