我正在异步使用HttpWebRequest类,如下面的代码所示(它只是windows应用程序):
private void StartWebRequest(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.BeginGetResponse(new AsyncCallback(FinishWebRequest), request);
}
private void FinishWebRequest(IAsyncResult result)
{
HttpWebResponse response = (result.AsyncState as HttpWebRequest).EndGetResponse(result) as HttpWebResponse;
Stream responseStream = response.GetResponseStream();
int num = 100000;
byte[] buffer = new byte[num];
int offset = 0;
while ((num2 = responseStream.Read(buffer, offset, 1000)) != 0)
{
offset += num2;
}
MemoryStream stream = new MemoryStream(buffer, 0, offset);
Bitmap bitmap = (Bitmap)Image.FromStream(stream);
bitmap.Save(@"z:\new.jpg");
response.Close();
responseStream.Close();
stream.Close();
}
有时我会收到错误:
The underlying connection was closed : An unexpected error occured on a send
无论如何都要解决这个问题?
答案 0 :(得分:2)
您必须将代码放在try和catch块中,如果发现错误,请尝试重新连接。您可以预定义试验次数的配额(例如,尝试最多3次),网络环境是不可预测的,因此您必须保持任何不可靠性。 BTW,在最后的试验之后不要忘记关闭流和连接