RestSharp JSON POST请求遇到错误请求

问题描述 投票:0回答:4

我正在使用RestSharp来发出包含JSON主体的POST请求。但我得到一个错误的请求错误。

因为我的JSON中有[]"",所以我决定使用Newtonsoft.Json。在使用它之前,我甚至看不到正在形成的JSON请求。

我愿意尝试MS httpwebrequest作为替代方案。

restClient = new RestClient();

restRequest = new RestRequest(ApiUrl, Method.POST, DataFormat.Json);

var myObject = "{ \"target\" : \"[5,5]\", \"lastseen\" : \"1555459984\" }";

var json = JsonConvert.SerializeObject(myObject);
restRequest.AddParameter("application/json", ParameterType.RequestBody);

restRequest.AddJsonBody(json);

请注意,我正在尝试将JSON卷曲转换为C#。请看下面:

curl -H 'Content-Type: application/json' -X POST -d '{ "target" : [5, 5], "lastseen" : "1555459984", "previousTargets" : [ [1, 0], [2, 2], [2, 3] ] }' http://santized/santized/santized

c# json post restsharp web-api-testing
4个回答
3
投票

您似乎过度序列化要发送的数据。

考虑创建一个对象,然后将其传递给AddJsonBody

//...

restClient = new RestClient();

restRequest = new RestRequest(ApiUrl, Method.POST, DataFormat.Json);

var myObject = new { 
    target = new []{ 5, 5 }, 
    lastseen = "1555459984",
    previousTargets = new []{
        new [] { 1, 0 }, 
        new [] { 2, 2 }, 
        new [] { 2, 3 } 
    }
};

restRequest.AddJsonBody(myObject); //this will serialize the object and set header

//...

qazxsw poi将内容类型设置为qazxsw poi并将对象序列化为JSON字符串。


1
投票

为什么不呢?

AddJsonBody

删除了序列化json字符串的行。


0
投票

你也可以使用:

application/json

0
投票

你可以做这个例子:

restClient = new RestClient();

restRequest = new RestRequest(ApiUrl, Method.POST, DataFormat.Json);

var myObject = "{ \"target\" : \"[5,5]\", \"lastseen\" : \"1555459984\" }";

restRequest.AddParameter("application/json", ParameterType.RequestBody);

restRequest.AddJsonBody(json);
© www.soinside.com 2019 - 2024. All rights reserved.