0

在一个非常简单的控制台应用程序中运行此代码:

try
{
    var request = WebRequest.Create("some url here") as HttpWebRequest;
    byte[] bytes = Encoding.ASCII.GetBytes("some JSON string here");
    request.Method = "POST";
    request.Host = "some host here";
    request.ContentLength = bytes.Length;
    request.KeepAlive = true;
    request.Headers.Add("Cache-Control", "no-cache");
    request.Headers.Add("Pragma", "no-cache");
    request.Headers.Add("Origin", "some host here");
    request.Headers.Add("X-Requested-With", "XMLHttpRequest");
    request.UserAgent =
        "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.71 Safari/537.36";
    request.Accept = "*/*";
    request.Referer = "host here";
    request.Headers.Add("Accept-Encoding", "gzip,deflate,sdch");
    request.Headers.Add("Accept-Language", "en-US,en;q=0.8");
    using (Stream newStream = request.GetRequestStream())
    {
         newStream.Write(bytes, 0, bytes.Length);
    }
    var response = request.GetResponse();
    var result = new StreamReader(response.GetResponseStream()).ReadToEnd();
}
catch (Exception)
{
    throw;
}

为什么request.GetRequestStream()挂起?

4

2 回答 2

2

HttpWebRequest 的 GetRequestStream 确保与远程端点的连接是打开的,并且在返回并允许您编写内容之前发送标头。如果该方法挂起,则可能意味着网络问题。

MSDN 声明如下:

当您在应用程序中启用网络跟踪时,此成员会输出跟踪信息。有关详细信息,请参阅网络跟踪。

对于调试,您可以使用网络跟踪 ( http://msdn.microsoft.com/en-us/library/hyb3xww8.aspx ) 以及像 wireshark 这样的数据包嗅探器。

于 2013-09-18T07:33:54.920 回答
0

request.Host = "some host here";从代码中删除该行。它必须解决你的问题。

于 2013-09-18T09:18:33.480 回答