Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpClient.GetAsync(url) returns 504 to a URL which works in the browser

Tags:

c#

httpclient

I can access a URL manually, but get a timeout when using .Net.

I have created a button to duplicate the scenario more easily. Sometimes I get an exception saying the task was cancelled, else a 504 error which follows this code snippet:

    private async void Button_Click_1(object sender, RoutedEventArgs e)
    {
        var url = "http://api.dailyfive.tv/index.php?task=REQUEST_REGIONS&session=TestWin8&app=4&model=TestWin8&ver=1.0.0.7&os=8&region=";
        var output = await ReadHttpResponse(url);
    }
    private async Task<string> ReadHttpResponse(string url)
    {
        try
        {
            using (HttpClient client = new HttpClient())
            {
                HttpResponseMessage response = await client.GetAsync(url);
                return await response.Content.ReadAsStringAsync();
            }
        }
        catch (Exception ex)
        {
        }
        return null;
    }

Here is the result:

<html>
<head><title>504 Gateway Time-out</title></head>
<body bgcolor="white">
<center><h1>504 Gateway Time-out</h1></center>
<hr><center>nginx/1.2.0</center>
</body>
</html>
like image 814
Peter Avatar asked Oct 07 '22 05:10

Peter


1 Answers

It looks like the server is sensitive to the client's user agent. When I added these lines to your sample code, the code sprang into life:

client.DefaultRequestHeaders.UserAgent.Clear();
client.DefaultRequestHeaders.UserAgent.ParseAdd("Chrome/22.0.1229.94");

(There may be a better way of doing it - I haven't used HttpClient before.)

As an aside, I hope you're not really swallowing exceptions like that...

like image 91
Jon Skeet Avatar answered Oct 11 '22 00:10

Jon Skeet