远程服务器返回错误 (400) Bad Request,状态 ProtocolError

The remote server returned an error (400) Bad Request, status ProtocolError

我在其他类似问题中找不到解决方案。 我收到远程服务器返回错误:(400) Bad Request error while 运行 以下代码。

string url = @"http://api.dwaybill.com/" + cid + 
               "/orders.json?v=" + version + "&key=" + key + 
               "&customer_number=" + customer_number + 
               "&password=" + password;

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
UTF8Encoding encoding = new UTF8Encoding();

byte[] bytes1 = encoding.GetBytes(@"{"Here is the json text that i testet and is correct"}");

request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = bytes1.Length;

using (Stream sendStream = request.GetRequestStream())
{
    sendStream.Write(bytes1, 0, bytes1.Length);
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
    using (Stream stream = response.GetResponseStream())
    {
        using (StreamReader reader = new StreamReader(stream))
        {
            html = reader.ReadToEnd();
        }
    }
}
Console.WriteLine(html);

通过 (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) 获取响应时,我收到 400 Bad Request 错误。

我该如何解决这个问题?我该怎么办?

编辑:这是我试图发出 post 请求的 API:https://github.com/digwaybill/Digital-Waybill-API

似乎错误是因为缺少 headers.

请在请求前添加以下headers格式:

request.Headers["X-My-Custom-Header"] = "the-value";

对于您的示例,它将是:

request.Headers["Accept"] = " application/json";

请更新 JSON 的行,如下所示。 Json 需要键和值。随意将 name 更新为任何其他字符串。双引号也干扰了必须转义的字符串格式。

byte[] bytes1 = encoding.GetBytes("{\"name\":\"Here is the json text that i testet and is correct\"}");