2011-09-02 699 views
5

请帮助我。 发送帖子后,我有webexception“获取响应流(ReadDone2):接收失败”错误。帮助摆脱这个错误。谢谢。获取响应流时出错(ReadDone2):接收失败

一段代码

try 
{ 
string queryContent = string.Format("login={0}&password={1}&mobileDeviceType={2}/", 
login, sessionPassword, deviceType); 
request = ConnectionHelper.GetHttpWebRequest(loginPageAddress, queryContent); 

using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())//after this line //occurs exception - "Error getting response stream (ReadDone2): Receive Failure" 
{ 

ConnectionHelper.ParseSessionsIdFromCookie(response); 

string location = response.Headers["Location"]; 
if (!string.IsNullOrEmpty(location)) 
{ 
string responseUri = Utils.GetUriWithoutQuery(response.ResponseUri.ToString()); 
string locationUri = Utils.CombineUri(responseUri, location); 
result = this.DownloadXml(locationUri); 
} 
response.Close(); 
} 
} 
catch (Exception e) 
{ 
errorCout++; 
errorText = e.Message; 
} 

// Methot GetHttpWebRequest

public static HttpWebRequest GetHttpWebRequest(string uri, string queryContent) 
    { 
     HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);    
     request.Proxy = new WebProxy(uri); 
     request.UserAgent = Consts.userAgent; 
     request.AutomaticDecompression = DecompressionMethods.GZip; 
     request.AllowWriteStreamBuffering = true; 
     request.AllowAutoRedirect = false; 

     string sessionsId = GetSessionsIdForCookie(uri); 
     if (!string.IsNullOrEmpty(sessionsId)) 
      request.Headers.Add(Consts.headerCookieName, sessionsId); 

     if (queryContent != string.Empty) 
     { 
      request.ContentType = "application/x-www-form-urlencoded"; 
      request.Method = "POST"; 
      byte[] SomeBytes = Encoding.UTF8.GetBytes(queryContent); 
      request.ContentLength = SomeBytes.Length; 
      using (Stream newStream = request.GetRequestStream()) 
      { 
       newStream.Write(SomeBytes, 0, SomeBytes.Length); 
      } 
     } 
     else 
     { 
      request.Method = "GET"; 
     } 

     return request; 
    } 
+0

你能后的ConnectionHelper类的代码(或者只是在GetHttpWebRequest方法)? – clarkb86

回答

0
using (Stream newStream = request.GetRequestStream()) 
{ 
    newStream.Write(SomeBytes, 0, SomeBytes.Length); 

    //try to add 
    newStream.Close(); 
} 
+1

当使用'using'关键字时,是否有必要显式调用Close()函数?我认为这个流在超出'使用'声明的范围时会自动处理/关闭。 –

+0

我也这么认为,但在实践中没有.Close()它不会发送请求。 – mironych

0

在我的情况下,服务器没有响应体。修复服务器后,“接收失败”消失。

所以,你有两个选择:

  1. 不要请求响应流,如果你能活着离不开它。

  2. 确保服务器发送响应正文。

    例如,而不是

    self.send_response(200) 
    self.wfile.close() 
    

    Python的服务器代码应该是

    self.send_response(200) 
    self.send_header('Content-type', 'text/plain') 
    self.end_headers() 
    self.wfile.write("Thanks!\n") 
    self.wfile.close() 
    
相关问题