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

  • 相关阅读:
    如何学习一门新技术
    linux atoi
    linux switch 跳转到 ”跳转至 case 标号“ 的错误
    from unittest import TestCase
    ensure that both new and old access_token values are available within five minutes, so that third-party services are smoothly transitioned.
    .BigInteger
    408
    Convert a string into an ArrayBuffer
    Optimal asymmetric encryption padding 最优非对称加密填充(OAEP)
    https://tools.ietf.org/html/rfc8017
  • 原文地址:https://www.cnblogs.com/raincedar/p/11017894.html
Copyright © 2011-2022 走看看