Search code examples
c#dotnet-httpclient

HttpClient.GetAsync is getting Internal Error (500) but Chrome gets a response


For some reason I am getting Internal Error 500 when using c# HttpClient. The URL doesn't respond with 500 error when using chrome/web browser or Postman.

The Test URL I am using is "https://onlinetools.ups.com/track/v1/details/asdfa"

When I access the URL directly via Chrome by pasting it in, it gets the below response

<CommonResponse>
    <response>
        <errors>
            <errors>
                <code>250003</code>
                <message>Invalid Access License number. Access Key not found</message>
            </errors>
        </errors>
    </response>
</CommonResponse>

It gets similar result for Postman (though in JSON format)

But when I try to do it via HttpClient I get an Internal 500 Error. The Test code is

        using (var client = new HttpClient())
        {
            var testResult = client .GetAsync("https://onlinetools.ups.com/track/v1/details/asdfa").Result;
        }

Does anyone ever seen something similar or know of a fix? This is a bit too deep for my limited knowledge.


Solution

  • To get the same response you need to set the Accept header in your request, like this

    client.DefaultRequestHeaders.Add("Accept", "application/json");
    var testResult = client.GetAsync("https://onlinetools.ups.com/track/v1/details/asdfa").Result;
    Console.WriteLine(testResult.Content.ReadAsStringAsync().Result);
    

    You will then receive a response in JSON as in Postman.

    Consider making it asynchronous. This is just an example to answer your question.