简体   繁体   中英

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

I couldn't find the solution in the other similar questions. I am getting The remote server returned an error: (400) Bad Request error while running the following code.

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);

While getting the response via (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) , I am getting 400 Bad Request error.

How can I solve this problem? What should I do?

edit: this is the API that Im trying to make a post request: https://github.com/digwaybill/Digital-Waybill-API

Seems the error is because of missing headers.

Please add the below headers before the request in the format:

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

For your example, it would be:

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

Please update the line for JSON as below. Json needs a key and value. Feel free to update the name to any other string. Also the double quotes is interfering with the string format, which has to be escaped.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM