远程服务器返回错误(400)错误的请求,状态为ProtocolError

时间:2018-12-25 09:08:30

标签: c# rest httpwebresponse bad-request http-response-codes

在其他类似问题中找不到解决方案。 我得到远程服务器返回错误:(400)运行以下代码时出现错误的请求错误。

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错误的请求错误。

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

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

1 个答案:

答案 0 :(得分:0)

错误似乎是由于缺少标题所致。

请在请求前以以下格式添加以下标头:

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

以您的示例为例,

name

请如下更新JSON行。杰森需要一个关键和价值。随时将byte[] bytes1 = encoding.GetBytes("{\"name\":\"Here is the json text that i testet and is correct\"}"); 更新为任何其他字符串。此外,双引号会干扰必须转义的字符串格式。

{{1}}