写了一个客户端软件向某个网站页面发起查询请求并获取返回的JSON数据,函数代码如下:
public string doGetRequest(string cookie, string url)
{
Uri uri = new Uri(url);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "GET";
request.AllowAutoRedirect = false;
request.Accept = "application/json";
request.ContentType = "application/x-www-form-urlencoded";
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.221 Safari/537.36 SE 2.X MetaSr 1.0";
if (cookie.Length > 0)
{
request.Headers.Add("Cookie", cookie);
}
HttpWebResponse response;
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
response = (HttpWebResponse)ex.Response;
StreamReader sr = new StreamReader(response.GetResponseStream());
MessageBox.Show(sr.ReadToEnd());
}
if (response.StatusCode != HttpStatusCode.OK)
{
MessageBox.Show("服务器返回请求错误!");
return "";
}
string encoding = response.ContentEncoding;
if (encoding == null || encoding.Length < 1)
{
encoding = "UTF-8"; //默认编码
}
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
string result = reader.ReadToEnd();
//释放资源
response.Close();
reader.Close();
return result;
}
调用该函数时传入事先获取的cookie和请求url,url的值如下(网站域名用*省略):
http://*********/tcatsds/tcaTsdApprover/searchAllTcatsd?APPLYNO=P20190098290
可是程序总是报错,说GetResponse返回502错误,查看返回的详细信息如下:
从返回的详细信息上看是无权访问该页面,但是我如果在浏览器中直接输入该url,是能看到返回的JSON数据的,实在想不通为什么,哪位大神能指导一下该怎么办?