2017-09-08 902 views
1

我有以下代碼:C#:System.Net.WebException:基礎連接已關閉

String url = // a valid url 
String requestXml = File.ReadAllText(filePath);//opens file , reads all text and closes it 
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(requestXml); 
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); 
request.Credentials = new NetworkCredential("DEFAULT\\Admin", "Admin"); 
request.ContentType = "application/xml"; 
request.ContentLength = bytes.Length; 
request.Method = "POST"; 
request.KeepAlive = false; 
Stream requestStream = request.GetRequestStream(); 
requestStream.Write(bytes, 0, bytes.Length); 
requestStream.Close(); 
HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
Stream responseStream = response.GetResponseStream(); 
return new StreamReader(responseStream).ReadToEnd(); 

在運行過程中,我發現了以下異常試圖讀取HTTPWebResponse

System.Net.WebException:底層連接已關閉:接收時發生意外錯誤。
---> System.IO.IOException:無法從傳輸連接讀取數據:建立的連接被主機中的軟件中止。在System.Net.Sockets.Socket.Receive(Byte []緩衝區,Int32偏移量,Int32大小,以及在System.Net.Sockets.Socket.Receive中創建的連接已被您的主機中的軟件中止
SocketFlags socketFlags)
at System.Net.Sockets.NetworkStream.Read(Byte [] buffer,Int32 offset,Int32 size)
at System.Net.Sockets.NetworkStream.Read(Byte [] buffer,Int32 offset,Int32 size )
在System.Net.PooledStream.Read(字節[]緩衝液,的Int32偏移的Int32大小)
在System.Net.Connection.SyncRead(HttpWebRequest的請求,布爾userRetrievedStream,布爾probeRead)

+0

https://stackoverflow.com/questions/21728773/the-underlying-connection-was-closed-an-unexpected-error-occurred-on-a-receiv – w0051977

+0

@ w0051977我有已經看到這個線程,我已經設置request.keepAlive = false。那麼是否有必要重寫GetWebRequest(Uri uri)方法? – user1168608

+3

刪除Close()方法並重試。您正試圖從您關閉的連接中讀取響應。 – jdweng

回答

1

在閱讀之前不要關閉流。這應該工作:

String url = // a valid url 
String requestXml = File.ReadAllText(filePath);//opens file , reads all text and closes it 
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(requestXml); 
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); 
request.Credentials = new NetworkCredential("DEFAULT\\Admin", "Admin"); 
request.ContentType = "application/xml"; 
request.ContentLength = bytes.Length; 
request.Method = "POST"; 
request.KeepAlive = false; 
using (Stream requestStream = request.GetRequestStream()) 
{ 
    requestStream.Write(bytes, 0, bytes.Length); 
    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) 
    { 
     using (Stream responseStream = response.GetResponseStream()) 
     { 
      using (StreamReader streamReader = new StreamReader(responseStream)) 
      { 
       return streamReader.ReadToEnd(); 
      } 
     } 
    } 
} 
相關問題