1

For a project, i've to use an API that uses the GET verb and which necessarily requires the "Content-type" property, but this isn't standard and i'd like to set this property to "application/json".

I'm using the C# HttpClient and after looking in the whole universe, I can't find a way to do it. I always have a "ProtocolViolationException", obviously...

Is there a way to use a "Content-type" and a "GET" request with HttpClient ?

I'm using this code

public async Task<HttpResponseMessage> GetAsync(string uri, double timeout = 0, string token = null)
    {
        using(var handler = new HttpClientHandler())
        {
            if(handler.SupportsAutomaticDecompression)
            {
                handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            }

            using(var client = new HttpClient(handler))
            {
                var request = new HttpRequestMessage(HttpMethod.Get, uri);

                HttpResponseMessage httpResponseMessage = null;

                if(timeout > 0)
                {
                    client.Timeout = TimeSpan.FromSeconds(timeout);
                }

                if(!string.IsNullOrWhiteSpace(token))
                {
                    request.Headers.Add("authorization", token);
                }

                request.Content = new StringContent("");
                request.Content.Headers.Remove("Content-type");
                request.Content.Headers.Add("Content-type", "application/json");

                httpResponseMessage = await client.SendAsync(request);

                return httpResponseMessage;
            }
        }
    }

Thanks in advance :)

1 Answers1

0

Do not set a Content-Type in the GET request. Instead, assuming that you would like to receive a JSON result, set the Accept header.

rogi1609
  • 438
  • 3
  • 8
  • 1
    Yes, generally "content" is just for POST and PUT, but the API i'm using requires "GET" and "Content-type", otherwise the API doesn't give any results, is there a way to do it ? – Arezki Saba May 30 '15 at 19:34