2011-09-02 693 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() 
    
相關問題