【问题标题】:Unable to read data from the transport connection: Stream Reader Error无法从传输连接读取数据:流读取器错误
【发布时间】:2013-04-17 09:16:59
【问题描述】:

以下代码抛出错误:
“无法从传输连接读取数据:连接已关闭。”-System.IO.IOException。
该方法接收一个 URL 作为参数,执行它并从网络服务器获取响应。

使用 Stream 读取响应时,while 循环内的行 liBytesRead = lStream.Read(lBytes, 0, 128); 会引发引用的错误。

public bool GetFromUrl(ref string psUrl, ref string rsResult, ref int piTimeoutSeconds)
{
  System.Text.StringBuilder lStringB = new System.Text.StringBuilder();

try {
    WebRequest lWebRequest = WebRequest.Create(psUrl);
    int liTimeout = piTimeoutSeconds * 1000;

    lWebRequest.Timeout = liTimeout;

    WebResponse lWebResponse = lWebRequest.GetResponse;
    Stream lStream = default(Stream);
    lStream = lWebResponse.GetResponseStream;

    byte[] lBytes = new byte[129];
    int liBytesRead = lStream.Read(lBytes, 0, 128);
    System.Text.Encoding lEncode = System.Text.Encoding.GetEncoding("utf-8");

    while (liBytesRead > 0) {
        lStringB.Append(lEncode.GetString(lBytes, 0, liBytesRead));
        liBytesRead = lStream.Read(lBytes, 0, 128);
    }
    lStream.Close();

    rsResult = lStringB.ToString();
    return true;
} catch (System.IO.IOException e) {
    rsResult = e.ToString();
    return false;
}
}

知道为什么会这样......
谢谢。

【问题讨论】:

    标签: c# asp.net


    【解决方案1】:

    看起来网络服务器在连接完成之前关闭了连接。
    试试

    HttpRequest.KeepAlive = false; 
    HttpRequest.ProtocolVersion = HttpVersion.Version10;
    

    更多详情请参考:http://sysrc.code4beer.org/2009/06/30/webrequest-unable-to-read-from-transport/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-15
      相关资源
      最近更新 更多