在一个非常简单的控制台应用程序中运行此代码:
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()
会挂起?
答案 0 :(得分:2)
HttpWebRequest的GetRequestStream确保在返回并允许您编写内容之前,打开与远程端点的连接并发送标头。如果该方法挂起,则可能意味着网络问题。
MSDN声明如下:
启用网络跟踪时,此成员会输出跟踪信息 在你的申请中。有关详细信息,请参阅网络跟踪。
对于调试,您既可以使用网络跟踪(http://msdn.microsoft.com/en-us/library/hyb3xww8.aspx),也可以使用像wireshark这样的数据包嗅探器。
答案 1 :(得分:0)
从代码中删除行request.Host = "some host here";
。它必须解决你的问题。