HttpClient 和 WebClient 返回 503 服务器不可用或 403 禁止

问题描述

在 C# 中,我尝试使用 WebClient 或 HttpClient 从 URL 检索文本响应。该 URL 在浏览器中有效。但是,当我使用 WebClient 或 HttpClient 时,我想使用的 http 服务出现 503 或 403 错误

我使用典型 URL 测试了我的 WebClient 和 HttpClient 例程,并且例程按预期工作。

服务 URL 为:“http://api.db-ip.com/v2/free/”,附加 IP 地址以完成 URL。

例如:“http://api.db-ip.com/v2/free/1.10.16.5”

示例在浏览器中显示的结果是纯文本:

{
    "ipAddress": "1.10.16.5","continentCode": "AS","continentName": "Asia","countryCode": "CN","countryName": "China","stateProv": "Guangdong","city": "Guangzhou Shi"
}

我在其他帖子中尝试了针对同一问题的各种建议答案。但是,对于该站点,问题仍然存在。我确认我完全在可接受的服务使用范围内 - 并且 URL 在我的开发 PC 上的浏览​​器中工作并与 curl 一起使用。

以下是我使用 WebClient 的典型 C# 代码。我的 HttpClient 代码有点复杂,涉及异步任务和等待;但结果大致相同。

using (WebClient client = new WebClient())
{
    string testURL = "http://api.db-ip.com/v2/free/1.10.16.5"
    string testResult = ""
    try
    {
        // tried Proxy,Encoding,and user-agent settings,no difference
        // client.Proxy = null;
        // client.Encoding = Encoding.UTF8;
        // client.Headers.Add("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
        testResult = client.DownloadString(testURL);
    }
    catch (Exception x)
    {
        Console.WriteLine("Error getting result from " + testURL);
        Console.WriteLine("Response Text> " + testResult);
        Console.WriteLine(x.Message);
        if (x.InnerException != null)
        {
            Console.WriteLine(x.InnerException.Message);
        }
    }
}

我尝试了各种 WebClient 参数都没有成功。我希望我缺少正确的参数来使其工作。

-=-=-=- 更新:以下 HttpClient 方法有效(感谢 @mxmissile)

// HttpClient instance lifecycle should be the Application's lifecycle per .NET recommendation
private static readonly HttpClient myHttpClient = new HttpClient();

public async Task<string> GeoLocationText_byIpAddressAsync(string ipAddress)
{
    string testURL = "http://api.db-ip.com/v2/free/1.10.16.5"
    string testResult = ""
    try
    {
        myHttpClient .DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:90.0) Gecko/20100101 Firefox/90.0");
        string testResult = await myHttpClient .GetStringAsync(testURL );
    }
    catch (Exception x)
    {
        Console.WriteLine("Error getting result from " + testURL);
        Console.WriteLine("Response Text> " + testResult);
        Console.WriteLine(x.Message);
        if (x.InnerException != null)
        {
            Console.WriteLine(x.InnerException.Message);
        }
    }
}

解决方法

以下代码现在使用@mxmissile 和@Riwen 描述的.UserAgent 属性对我有用。他们应该因为这个答案而受到赞扬。

// HttpClient instance lifecycle should be the Application's lifecycle per .NET recommendation
private static readonly HttpClient myHttpClient = new HttpClient();

public async Task<string> GeoLocationText_byIpAddressAsync(string ipAddress)
{
    string testURL = "http://api.db-ip.com/v2/free/1.52.235.161"
    string testResult = ""
    try
    {
        myHttpClient .DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:90.0) Gecko/20100101 Firefox/90.0");
        string testResult = await myHttpClient .GetStringAsync(testURL );
    }
    catch (Exception x)
    {
        Console.WriteLine("Error getting result from " + testURL);
        Console.WriteLine("Response Text> " + testResult);
        Console.WriteLine(x.Message);
        if (x.InnerException != null)
        {
            Console.WriteLine(x.InnerException.Message);
        }
    }
}

测试结果为:

{
    "ipAddress": "1.52.235.161","continentCode": "AS","continentName": "Asia","countryCode": "VN","countryName": "Vietnam","stateProv": "Hanoi","city": "Hanoi"
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...