【发布时间】:2021-09-23 16:42:21
【问题描述】:
在 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 代码有点复杂,涉及 async Task 和 await;但结果大致相同。
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);
}
}
}
【问题讨论】:
-
免费配额是每天 1000 个查询。由于我还没有让它工作,我可能已经尝试了大约 10 到 20 个 IP 地址。此外,使用网络浏览器或 curl 没有问题
-
尝试指定
User-Agent标头。 -
像@Riwen 提到的那样添加 UserAgent 对我有用:gist.github.com/mxmissile/a32ceeaeda6f63365d9930d7399497e8
-
它与@Riwen 的用户代理建议一起工作。谢谢你们@mxmissile!!!
标签: c# webclient dotnet-httpclient http-status-code-503