HttpWebRequest导致应用程序挂起

时间:2015-01-09 23:00:08

标签: c# httpwebrequest

我有一个奇怪的问题。我在Visual Studio 2013中创建了一个应用程序,该应用程序在Windows中运行良好。然后我将它移植到Mono,因为我需要应用程序在Linux控制台中运行。

该应用程序在Mono中工作正常,但现在它已停止在Windows中工作。源代码完全相同。它实际上是Mono源代码的复制和粘贴。当我在Windows中运行应用程序时,它只是提供了一个黑色的控制台窗口,并且"挂起"。这是悬挂的代码:

static void Main(string[] args)
{
    string orders = GetLoginHtml();

    Console.WriteLine(orders);
}

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);

        // The next line is where it hangs

        using (var sr = new StreamReader(request.GetResponse().GetResponseStream()))
        {
            string html = sr.ReadToEnd();
            string galxValue = ParseOutValue(html, "GALX");

            return GetLoginHtml2(galxValue, cookieJar);
        }
    }
}

我评论了线路悬挂的位置。我不知道为什么,至少它没有给我一个超时错误。我跑了小提琴手,我看到它试图出去,但Fiddler只是立即报告了一个封闭的连接。如果我使用浏览器访问它,我的互联网工作正常,URL工作正常。有什么建议?

1 个答案:

答案 0 :(得分:1)

我终于弄明白了这个问题。我发布这个答案,希望它可以帮助其他人在将来不可避免的头疼。

现在是我的工作代码:

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);
}

我的猜测是我的requestStream在获取响应流之前没有被垃圾收集和关闭。我认为响应流是在请求流完成写入字节之前打开并读取的。在开始阅读之前,Mono必须足够聪明才能完成写作。无论如何,它现在在Windows和Mono中工作! Silly .NET垃圾收集器。