How do you set the Content-Type header for an HttpClient request?

后端 未结 14 2219
暗喜
暗喜 2020-11-22 03:57

I\'m trying to set the Content-Type header of an HttpClient object as required by an API I am calling.

I tried setting the Content-Ty

相关标签:
14条回答
  • 2020-11-22 04:14

    I end up having similar issue. So I discovered that the Software PostMan can generate code when clicking the "Code" button at upper/left corner. From that we can see what going on "under the hood" and the HTTP call is generated in many code language; curl command, C# RestShart, java, nodeJs, ...

    That helped me a lot and instead of using .Net base HttpClient I ended up using RestSharp nuget package.

    Hope that can help someone else!

    0 讨论(0)
  • 2020-11-22 04:15

    For those who troubled with charset

    I had very special case that the service provider didn't accept charset, and they refuse to change the substructure to allow it... Unfortunately HttpClient was setting the header automatically through StringContent, and no matter if you pass null or Encoding.UTF8, it will always set the charset...

    Today i was on the edge to change the sub-system; moving from HttpClient to anything else, that something came to my mind..., why not use reflection to empty out the "charset"? ... And before i even try it, i thought of a way, "maybe I can change it after initialization", and that worked.

    Here's how you can set the exact "application/json" header without "; charset=utf-8".

    var jsonRequest = JsonSerializeObject(req, options); // Custom function that parse object to string
    var stringContent = new StringContent(jsonRequest, Encoding.UTF8, "application/json");
    stringContent.Headers.ContentType.CharSet = null;
    return stringContent;
    

    Note: The null value in following won't work, and append "; charset=utf-8"

    return new StringContent(jsonRequest, null, "application/json");
    

    EDIT

    @DesertFoxAZ suggests that also the following code can be used and works fine. (didn't test it myself, if it work's rate and credit him in comments)

    stringContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
    
    0 讨论(0)
  • 2020-11-22 04:17

    Some extra information about .NET Core (after reading erdomke's post about setting a private field to supply the content-type on a request that doesn't have content)...

    After debugging my code, I can't see the private field to set via reflection - so I thought I'd try to recreate the problem.

    I have tried the following code using .Net 4.6:

    HttpRequestMessage httpRequest = new HttpRequestMessage(HttpMethod.Get, @"myUrl");
    httpRequest.Content = new StringContent(string.Empty, Encoding.UTF8, "application/json");
    
    HttpClient client = new HttpClient();
    Task<HttpResponseMessage> response =  client.SendAsync(httpRequest);  //I know I should have used async/await here!
    var result = response.Result;
    

    And, as expected, I get an aggregate exception with the content "Cannot send a content-body with this verb-type."

    However, if i do the same thing with .NET Core (1.1) - I don't get an exception. My request was quite happily answered by my server application, and the content-type was picked up.

    I was pleasantly surprised about that, and I hope it helps someone!

    0 讨论(0)
  • 2020-11-22 04:18

    For those who didn't see Johns comment to carlos solution ...

    req.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
    
    0 讨论(0)
  • 2020-11-22 04:22

    The content type is a header of the content, not of the request, which is why this is failing. AddWithoutValidation as suggested by Robert Levy may work, but you can also set the content type when creating the request content itself (note that the code snippet adds application/json in two places-for Accept and Content-Type headers):

    HttpClient client = new HttpClient();
    client.BaseAddress = new Uri("http://example.com/");
    client.DefaultRequestHeaders
          .Accept
          .Add(new MediaTypeWithQualityHeaderValue("application/json"));//ACCEPT header
    
    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "relativeAddress");
    request.Content = new StringContent("{\"name\":\"John Doe\",\"age\":33}",
                                        Encoding.UTF8, 
                                        "application/json");//CONTENT-TYPE header
    
    client.SendAsync(request)
          .ContinueWith(responseTask =>
          {
              Console.WriteLine("Response: {0}", responseTask.Result);
          });
    
    0 讨论(0)
  • 2020-11-22 04:23

    try to use TryAddWithoutValidation

      var client = new HttpClient();
      client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json; charset=utf-8");
    
    0 讨论(0)
提交回复
热议问题