HttpClient.GetAsync(url)将504返回到可在浏览器中使用的URL [英] HttpClient.GetAsync(url) returns 504 to a URL which works in the browser

查看:236
本文介绍了HttpClient.GetAsync(url)将504返回到可在浏览器中使用的URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以手动访问URL,但是使用.Net时会超时.

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

我创建了一个按钮,可以更轻松地复制场景.有时我会收到一个异常消息,说明任务已被取消,否则出现如下代码段所示的504错误:

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;
    }

这是结果:

<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>

推荐答案

服务器似乎对客户端的用户代理敏感.当我将这些行添加到您的示例代码中时,该代码就浮出水面了:

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");

(可能有更好的方法-我以前没有使用过HttpClient.)

(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...

这篇关于HttpClient.GetAsync(url)将504返回到可在浏览器中使用的URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆