C# - HTTPWebRequest没有返回任何内容

时间:2017-03-30 05:41:42

标签: c# httpwebrequest httpwebresponse

所以没有fiddler打开,我的代码似乎没有做任何事情! 但随着它打开,它的工作正常吗?!什么?

HttpWebRequest init = (HttpWebRequest)WebRequest.Create("https://accounts.spotify.com/en/login?continue=https:%2F%2Fwww.spotify.com%2Fus%2Faccount%2Foverview%2F");
init.Method = "GET";
init.UserAgent = "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36";
init.Timeout = 8000;
HttpWebResponse resp1 = (HttpWebResponse)init.GetResponse();

线程(在我的情况下是ThreadPool线程),只是冻结,而不是结束,只会因为无法连接而冻结,而try catch甚至看起来都不起作用。

如果我将小提琴设置上的端口更改为8888以外的任何其他内容并且让Fiddler打开,它会再次开始冻结,这意味着它会以某种方式链接到8888。但它根本没有在我的代码中引用。

固定!
发现它是由于没有关闭造成的! resp1.close()。 谢谢大家!

1 个答案:

答案 0 :(得分:0)

你在你的代码中写的是正确的。尝试调试此代码并查看您获得的响应,注意 responseBody HtmlResult

HttpWebRequest init = (HttpWebRequest)WebRequest.Create("https://accounts.spotify.com/en/login?continue=https:%2F%2Fwww.spotify.com%2Fus%2Faccount%2Foverview%2F");
init.Method = "GET";
init.UserAgent = "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36";
init.Timeout = 8000;
HttpWebResponse resp1 = (HttpWebResponse)init.GetResponse();
HttpStatusCode sc = resp1.StatusCode;
String sd = resp1.StatusDescription;
string HtmlResult = "";
string responseBody = "";
using (System.IO.Stream rspStm = resp1.GetResponseStream())
{
    using (System.IO.StreamReader reader = new System.IO.StreamReader(rspStm))
    {
        HtmlResult = HtmlResult +
                "Response Description: " + resp1.StatusDescription;
        HtmlResult = HtmlResult +
                "Response Status Code: " + resp1.StatusCode;
        HtmlResult = HtmlResult + "\r\n\r\n";
        responseBody = reader.ReadToEnd();
    }
}