HttpWebRequest只是挂在一台电脑上

本文关键字:一台 电脑 HttpWebRequest | 更新日期: 2023-09-27 18:33:44

我有一段代码出去,对谷歌钱包做了一个HttpWebRequest。代码在我的所有机器上都运行良好,除了我现在正在使用的这台计算机。这台计算机上的互联网工作得很好(因为我现在正在使用它来输入这个问题),而且我们没有代理服务器在工作。

问题是它只是挂起。它甚至不会超时。它只是挂起,没有错误消息或任何东西,我必须强制关闭它。这是代码:

    private static string GetLoginHtml()
    {
        var request = (HttpWebRequest)WebRequest.Create(LoginUrl);
        var cookieJar = new CookieContainer();
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.CookieContainer = cookieJar;
        using (var requestStream = request.GetRequestStream())
        {
            string content = "Email=" + Username + "&Passwd=" + Password;
            requestStream.Write(Encoding.UTF8.GetBytes(content), 0, Encoding.UTF8.GetBytes(content).Length);
            using (var sr = new StreamReader(request.GetResponse().GetResponseStream()))
            {
                string html = sr.ReadToEnd();
                string galxValue = ParseOutValue(html, "GALX");
                return GetLoginHtml2(galxValue, cookieJar);
            }
        }
    }

逐步执行Visual Studio调试器上的代码,我知道当它点击以下行时它会挂起:

using (var sr = new StreamReader(request.GetResponse().GetResponseStream()))

具体来说,request.GetResponse()部分是悬挂的东西。运行小提琴手,我看到的只是一个灰色条目,如下所示:

 3     200    HTTP            Tunnel to     accounts.google.com:443            0

没有别的了。无响应正文。有人对可能发生的事情有任何建议吗?它只发生在这台计算机上的事实告诉我,这可能不是编程问题。

HttpWebRequest只是挂在一台电脑上

我终于弄清楚了这个问题。我发布这个答案是希望它可以帮助其他人在未来遇到一些不可避免的挠头。

这是我现在的工作代码:

private static string GetLoginHtml()
{
    var request = (HttpWebRequest)WebRequest.Create(LoginUrl);
    var cookieJar = new CookieContainer();
    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";
    request.CookieContainer = cookieJar;
    using (var requestStream = request.GetRequestStream())
    {
        string content = "Email=" + Username + "&Passwd=" + Password;
        requestStream.Write(Encoding.UTF8.GetBytes(content), 0, Encoding.UTF8.GetBytes(content).Length);
    }
    using (var sr = new StreamReader(request.GetResponse().GetResponseStream()))
    {
        string html = sr.ReadToEnd();
        string galxValue = ParseOutValue(html, "GALX");
        return GetLoginHtml2(galxValue, cookieJar);
    }
}
我的

猜测是,在获得响应流之前,我的请求流没有被垃圾回收和关闭。我认为响应流在请求流完成写入其字节之前被打开并读取。愚蠢的.NET垃圾回收器