HttpWebResponse Async 底层连接已关闭:发送时发生意外错误
我异步使用 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();
}
有时我会收到该错误:
底层连接已关闭:发送时发生意外错误
有办法解决这个问题吗?
谢谢
I m using HttpWebRequest class asynchronously as code below (its just windows application)
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();
}
sometimes i get that error:
The underlying connection was closed : An unexpected error occured on a send
Is there anyway to solve this issue?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在从远程服务器分块读取数据,但在某些时候,对远程服务器的传出请求失败。
至于为什么,请检查是否存在内部异常。您可能需要使用 Fiddler 或其他代理之类的东西来确定远程服务器关闭您的连接的原因。
顺便问一下,您读取 1000 字节块是否有某种原因?我突然想到,直接从服务器流式传输到您指定的 100kb 数组中可能会更好。而且,还要确保该缓冲区对于您的图像来说足够大......
You're reading data in chunks from a remote server, but at some point the outgoing request to the remote server is failing.
As to why, check to see if there's an inner exception. It may be that you'll need to use something like e.g. Fiddler or another proxy to establish why the remote server is closing your connection.
Incidentally, is there some reason why you're reading in 1000 byte blocks? It strikes me that you may be better off just streaming directly from the server into the 100kb array you've specified. And, also, make sure that that buffer is large enough for your image...