简体   繁体   中英

Why do I get a server timeout calling an API via HttpClient but Postman is fine?

I am trying to make a GET request to a RESTful service but the .NET HttpClient is receiving a timeout, but via Postman this returns an expected response (an error response, since I'm not yet "logged in") within seconds.

What I've tried:

  1. I have checked the URLs are the same and they are.
  2. I thought perhaps Postman's automagical headers are the issue, but after setting these in the HttpClient I still receive a timeout.
  3. If I increase the timeout on the HttpClient I still get a timeout from the server ( (504) Gateway Timeout ).
Client = new HttpClient(new HttpClientHandler()
{
    AutomaticDecompression = System.Net.DecompressionMethods.GZip
});
var objTask = Client.GetStringAsync(objUrl);
objTask.Wait();
strResponse = objTask.Result;
strResponse = Client.GetStringAsync(objUrl).Result;

Why am I receiving a timeout via HttpClient?

Note:

Our WebApi is calling our WCF Service, which in turn is calling the 3rd party RESTful service via HttpClient---for security reasons I can't call the 3rd party API directly from our WebApi controller. The website is based on the .NET 4.0 Framework.

With lots of help from @jdweng and @gunr2171, I've realised the issue was due to the proxy stored in the App.Config on the self-hosted WCF Services. If I commented this out, I wouldn't get a time-out issue.

The HttpClient constructor can take in a HttpClientHandler , which has a Proxy property where you can bypass the local proxy as so:

return new HttpClient(new HttpClientHandler()
{
    AutomaticDecompression = System.Net.DecompressionMethods.GZip,
    Proxy = new WebProxy()
    {
        BypassProxyOnLocal = true
    }
})
{
    BaseAddress = new Uri("https:\\my.service")
};

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