我正在尝试使用以下代码将以下json webservice https://mtgox.com/code/data/getDepth.php的结果放入字符串中。
using (WebClient client = new WebClient())
{
string data = client.DownloadString("https://mtgox.com/code/data/getDepth.php");
}
但它总是返回超时异常而没有数据。我打算使用fastjson将响应转换为对象,并期望这是一个困难的部分,而不是返回页面内容。
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://mtgox.com/code/data/getDepth.php");
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
string data = sr.ReadToEnd();
}
}
也导致了同样的错误。谁能指出我做错了什么?
答案 0 :(得分:3)
class Program
{
static void Main()
{
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.UserAgent] = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0) Gecko/20100101 Firefox/4.0";
var result = client.DownloadString("https://mtgox.com/code/data/getDepth.php");
Console.WriteLine(result);
}
}
}
请注意,我正在指定一个用户代理HTTP标头,因为该网站似乎正在期待它。
答案 1 :(得分:0)
request.KeepAlive = false
解决了我的问题。试试这个:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://mtgox.com/code/data/getDepth.php");
request.KeepAlive = false;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
string data = sr.ReadToEnd();
}
}