尝试两次创建get请求。但是第二个请求总是抛出带有消息的WebException:"底层连接已关闭:连接意外关闭。"
这是我使用的代码spinet
public string Get(string url)
{
string strResult = "";
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.CookieContainer = new CookieContainer();
request.UserAgent = this.UserAgent;
request.KeepAlive = false;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream, Encoding.UTF8);
strResult = reader.ReadToEnd();
response.Close();
}
catch (Exception ex)
{
//Todo
}
return strResult;
}
我要求url
如果我启动fiddler似乎第二次请求正常工作。 如果我使用HttpClient类似乎也可以。
答案 0 :(得分:0)
当你启动fiddler时,请求之间是否有任何延迟(你是否在中间点击了一个断点)。也许在您的通话之间添加一个快速Thread.Sleep(250);
。
要做的另一点,添加一些使用语句来关闭一次性类。
try {
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.CookieContainer = new CookieContainer();
request.UserAgent = this.UserAgent;
request.KeepAlive = false;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) {
strResult = reader.ReadToEnd();
response.Close();
}