【问题标题】:The remote server returned an error (400) Bad Request, status ProtocolError远程服务器返回错误 (400) Bad Request, status ProtocolError
【发布时间】:2018-12-25 09:08:29
【问题描述】:

我在其他类似问题中找不到解决方案。 我收到 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);

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

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

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

【问题讨论】:

  • 我不熟悉rest api,但您不需要关闭/刷新请求。您能否单步执行您的代码并发现错误发生的时间?
  • 如果你使用“using()”你不需要关闭/刷新@PeterSmith
  • @PeterSmith 代码出现在这里 (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) 并且状态是协议错误
  • 检查url的内容是否正确。 Bad request 表示“网关 [is] 无法处理提供的请求 URI,或者 HTTP 请求本身无效”。所以也许url 只是不正确/无效/包含空格或类似的东西

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


【解决方案1】:

似乎错误是因为缺少标题。

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

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\"}");

【讨论】:

  • 我添加了它,但我仍然收到 400 个错误请求
  • 我试过了,我的 json 数据似乎有问题:“状态”:400,“错误”:“发生 JSON 解析错误:缺少'}':ntact\”:{\ r\n \r\n缺少'}': ntact\": {\r\n \r\n缺少']': ntact\": {\r\n \r\n缺少'}': ntact\": { \r\n \r\n", "body": " } @Habeeb
  • 这是字符串 {"customer_number":"DYN833", "cost_center": "AJ Omnicare", "order_type": "Delivery", "ready_time": "Tue, 08 Jan 2013 08: 58:59", "round_trip": false, "route_stops": [{"company": "my company Pickup", "address": "1639 11th Street", "suite": "210", "city": "圣莫尼卡”,“州”:“CA”,“邮政编码”:“90049”,“国家”:“美国”,“联系人”:{“姓名”:“布拉德利·斯奈德”,“电话”:“8005753510” }]} 它继续。 @Habeeb
  • @bs你用的Json字符串是不是格式和结构不好?
  • Json 数据错误,我必须从文档中删除一些内容才能使其正常工作。@Habeeb
猜你喜欢
  • 2010-12-13
  • 1970-01-01
  • 2013-04-20
  • 2012-12-25
  • 1970-01-01
  • 1970-01-01
  • 2020-06-24
  • 1970-01-01
相关资源
最近更新 更多