【问题标题】:StatusCode: BadRequest - When calling RestAPI using RestSharp状态代码:错误请求 - 使用 RestSharp 调用 Rest API 时
【发布时间】:2016-09-25 07:55:58
【问题描述】:

我正在调用 RestAPI 并以 json 格式发送数据。使用 RestSharp 作为客户端。

具有以下功能。请看一下。

public HttpStatusCode  CreatOrder(OrderRequest order,string token)
{
    var client = new RestClient("this is url of api");
    request.AddHeader("Authorization", token);
    var json = JsonConvert.SerializeObject(order); //using Json.Net 
    request.AddJsonBody(order);
    request.Method = Method.POST;
    request.AddHeader("Content-Type", "application/json; charset=utf-8");
    var response = client.Execute(request);
    return response.StatusCode;
}

在调试过程中我可以看到以下 json。

"{\"waypoints\":[{\"exactLatLng\":[{\"lat\":123.0,\"lng\":234.0}],\"premise\":null,\"houseNumber\":null,\"street\":null,\"subLocality\":null,\"locality\":null,\"city\":null,\"district\":null,\"province\":null,\"country\":null,\"postalCode\":null,\"countryCode\":null,\"poiName\":null,\"placeLatLng\":[{\"lat\":123.0,\"lng\":234.0}]}],\"extraOptions\":null,\"client\":{\"clientId\":null,\"name\":\"NumanTest\",\"phone\":\"1213123\",\"imageUrl\":null},\"name\":\"NumanTest\",\"notes\":null,\"unitOfLength\":[],\"tripDistance\":null,\"tripDuration\":null,\"pickupTime\":null,\"numberOfSeats\":null,\"vehicleType\":[],\"tariffType\":[],\"paymentMethods\":[],\"prepaid\":null,\"tariffId\":null}"

但我总是收到错误的响应。

"StatusCode: BadRequest, Content-Type: application/json; charset=utf-8, Content-Length: 2325)"

你能帮我解决这个问题吗?

非常感谢。

【问题讨论】:

    标签: c# .net json rest restful-url


    【解决方案1】:

    您可能还必须将Content-Type-header 添加到请求中:

    request.AddHeader("Content-Type", "application/json; charset=utf-8");
    

    此外,您可以使用像 Fiddler 这样的网络调试代理来查看发送到服务的实际 http 请求。

    【讨论】:

    • 谢谢哥们。但是添加内容类型后,我得到了相同的结果
    • 您确定发布的内容正确吗?你的order-object 序列化是否正确?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-10
    • 1970-01-01
    • 2021-09-28
    • 1970-01-01
    • 2015-06-12
    • 2020-02-20
    • 1970-01-01
    相关资源
    最近更新 更多