[英]Receive data from server using POST method and with a request body using WebClient in C#
I am trying to receive data back from the server using POST method and the request should have a body.我正在尝试使用 POST 方法从服务器接收数据,并且请求应该有一个正文。 I am using WebClient for this and trying to get the response back in string.
我为此使用 WebClient 并尝试以字符串形式获取响应。 I know we can use HttpClient to achieve this.
我知道我们可以使用 HttpClient 来实现这一点。 But I want to use WebClient for this specific instance.
但我想为这个特定的实例使用 WebClient。
I went through this post and tried UploadString
and the response gives me a 400 BAD Request.我浏览了这篇文章并尝试了
UploadString
并且响应给了我一个 400 BAD 请求。
using (var wc = new WebClient())
{
wc.Headers.Add("Accept: application/json");
wc.Headers.Add("User-Agent: xxxxxxx");
wc.Headers.Add($"Authorization: Bearer {creds.APIKey.Trim()}");
var jsonString = JsonConvert.SerializeObject(new UserRequestBody
{
group_id = userDetails.data.org_id
});
var response = wc.UploadString("https://api.xxxxx.yyy/v2/users", "POST", jsonString);
}
I tested the end point using Postman (with the request header having an api key and the request body in JSON) and it works fine.我使用 Postman 测试了端点(请求 header 具有 api 密钥和 JSON 中的请求正文),它工作正常。
I know I haven't formatted the request right.我知道我没有正确格式化请求。 Can someone please help me.
有人可以帮帮我吗。
Big Thanks to @Santiago Hernández.非常感谢@Santiago Hernández。 The issue was using
wc.Headers.Add("Accept: application/json");
问题是使用
wc.Headers.Add("Accept: application/json");
in the request header.在请求 header 中。 Changing it to
wc.Headers.Add("Content-Type: application/json");
将其更改为
wc.Headers.Add("Content-Type: application/json");
returned a 200 Ok response.返回 200 Ok 响应。 The code modification is as follows
代码修改如下
using (var wc = new WebClient())
{
wc.Headers.Add("Content-Type: application/json");
wc.Headers.Add("User-Agent: xxxxxxx");
wc.Headers.Add($"Authorization: Bearer {creds.APIKey.Trim()}");
var jsonString = JsonConvert.SerializeObject(new UserRequestBody
{
group_id = userDetails.data.org_id
});
var response = wc.UploadString("https://api.xxxxx.yyy/v2/users", "POST", jsonString);
}
Accept
tells the server the kind of response the client will accept and Content-type
is about the payload/content of the current request or response. Accept
告诉服务器客户端将接受的响应类型, Content-type
是关于当前请求或响应的有效负载/内容。 Do not use Content-type
if the request doesn't have a payload/ body.如果请求没有有效负载/正文,请不要使用
Content-type
。
More information about this can be found here .可以在此处找到有关此的更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.