Http客户端调用api期间传递内容的正确方法

时间:2019-06-06 05:18:48

标签: c# httpclient

下面是POST API调用的代码段,其中我停留在错误位置:

  

错误请求

在网络上搜索后,我了解到,如果您在执行post api调用时未遵循正确的有效负载语法或传递正确的有效负载数据,则会收到此错误。

到目前为止,我尝试了不同的方法,但不幸的是,这些方法都无效。

// payload data's class represantation,
    public class DNCAddressInfo
        {
            [JsonProperty("dncAddress")]
            public string DNCAddress { get; set; }
            [JsonProperty("checkForPhoneRejection")]
            public bool CheckForPhoneRejection { get; set; }
            [JsonProperty("checkForPhoneFormats")]
            public bool CheckForPhoneFormats { get; set; }
        }

第一次尝试:

DNCAddressInfo dncObj = GetPayloadData();
string payload = JsonConvert.SerializeObject(dncObj);
var content = new StringContent(payload, Encoding.UTF8, "application/json");
HttpResponseMessage response = await _client.PostAsJsonAsync(url, content).ConfigureAwait(false); // response: error code: 400 , bad request

第二次尝试:

    DNCAddressInfo dncObj = GetPayloadData();
JObject jsonObject = new JObject
            {
                ["dncAddress"] = JsonConvert.SerializeObject(dncObj.DNCAddress),
                ["checkForPhoneRejection"] = JsonConvert.SerializeObject(dncObj.CheckForPhoneRejection),
                ["checkForPhoneFormats"] = JsonConvert.SerializeObject(dncObj.CheckForPhoneFormats)
            };

 var content = new StringContent(jsonObject.ToString(), Encoding.UTF8, "application/json");
 HttpResponseMessage response = await _client.PostAsJsonAsync(url, content).ConfigureAwait(false);// response: error code: 400 , bad request

第三次尝试:

string payload = "{\"dncAddress\": \"91#1231123\", \"checkForPhoneRejection\": false, \"checkForPhoneFormats\": false}"; // sample payload data taken from api providers document
var content = new StringContent(payload, Encoding.UTF8, "application/json");
HttpResponseMessage response = await _client.PostAsJsonAsync(url, content).ConfigureAwait(false); // response: error code: 400 , bad request

这三种方法均导致相同的错误,

StatusCode: 400, ReasonPhrase: '400'

Request header is , 
Headers = {Authorization: Basic XXXXX;
Accept: application/json
X-Requested-With: rest
Cache-Control: no-cache
}

邮递员的回复看起来还不错。这是相同的快照。

Postman response

我在这里做错什么了吗?还是错过了什么?

2 个答案:

答案 0 :(得分:4)

使用PostJsonAsync方法,您无需手动将对象序列化为json,只需将其原样传递即可:

DNCAddressInfo dncObj = GetPayloadData();
HttpResponseMessage response = await _client.PostAsJsonAsync(url, dncObj).ConfigureAwait(false);

或者您可以使用较新的HttpClient.PostAsync

DNCAddressInfo dncObj = GetPayloadData();
string payload = JsonConvert.SerializeObject(dncObj);
var content = new StringContent(payload, Encoding.UTF8, "application/json");
HttpResponseMessage response = await _client.PostAsync(url, content).ConfigureAwait(false);

参考文献: HttpClient.PostAsync Method HttpClientExtensions.PostAsJsonAsync Method

答案 1 :(得分:0)

“ PostAsJsonAsync”方法序列化内部的数据。当您将“ StringContent”传递给此方法时,HttpClient会将“ StringContent”序列化为Json并发送错误的数据。

尝试使用“ PostAsync”代替“ PostAsJsonAsync”。