WebRequest 接收 远程服务器返回错误:(403) 禁止访问



当我在Chrome浏览器中访问此URL时,它可以工作,我可以在那里看到一个字符串: https://cex.io/api/ticker/BTC/USD

但是,当我尝试使用以下代码请求上述 URL 时。我确实收到此错误消息:远程服务器返回错误:(403( 禁止访问

我想知道代码可能有什么问题,或者我是否需要添加或更改某些内容以返回字符串,就像我们在 chrome 浏览器中所做的那样?

public void request()
{
String responseBody = "";
String requestString = "https://cex.io/api/ticker/BTC/USD";
try
{
//Make the request
var request = (HttpWebRequest)WebRequest.Create(requestString);
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)";
request.Timeout = 15000;
request.Method = "GET"; //GET, POST
request.Accept = "application/json";
request.ContentType = "application/json; charset=utf-8";
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
var stream = response.GetResponseStream();
using (var reader = new StreamReader(stream))
{
try
{
responseBody = reader.ReadToEnd();
reader.Close();
}
catch { }
}
response.Close();
response.Dispose();
responseBody = responseBody.ToLower();
}
}
catch (WebException ex)
{
//Show Error
MessageBox.Show(ex.ToString());
}
MessageBox.Show(responseBody);
}

我的猜测是有问题的网站不支持IE6浏览器系列,但您将其指定为用户代理。 您可以删除它或将其更改为其他浏览器,代码将起作用。 我的建议是完全删除它,因为您只是发出数据请求以获取 JSON,因此您是什么"浏览器"并不重要。 您可以在这篇SO帖子中阅读有关UserAgent及其用途的更多信息 HttpWebRequest.UserAgent : 它有什么作用

该网站有一个标准用户代理列表:http://www.useragentstring.com/pages/useragentstring.php

这会将您的用户代理设置为 Mozilla 2.2。

request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; rv:2.2) Gecko/20110201";

最新更新