简体   繁体   中英

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. I am using WebClient for this and trying to get the response back in string. I know we can use HttpClient to achieve this. But I want to use WebClient for this specific instance.

I went through this post and tried UploadString and the response gives me a 400 BAD Request.

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. 在此处输入图像描述

I know I haven't formatted the request right. Can someone please help me.

Big Thanks to @Santiago Hernández. The issue was using wc.Headers.Add("Accept: application/json"); in the request header. Changing it to wc.Headers.Add("Content-Type: application/json"); returned a 200 Ok response. 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. Do not use Content-type if the request doesn't have a payload/ body.

More information about this can be found here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM