2009-06-18 63 views
14

看哪代碼:如何在發佈數據後讀取WebClient響應?

using (var client = new WebClient()) 
{ 
    using (var stream = client.OpenWrite("http://localhost/", "POST")) 
    { 
     stream.Write(post, 0, post.Length); 
    } 
} 

現在,我該如何讀取HTTP輸出?

+0

另見http://stackoverflow.com/questions/1694388/webclient-vs-httpwebrequest-httpwebresponse。 – DuckMaestro 2015-01-14 19:49:30

回答

19

它看起來像你有一個byte[]的數據發佈;在這種情況下,我想你會發現它更容易使用:

byte[] response = client.UploadData(address, post); 

如果響應是文本,一樣的東西:

string s = client.Encoding.GetString(response); 

(或您的Encoding選擇 - 也許Encoding.UTF8

+0

如果我沒有嘗試讀取HTTP 500響應,這將變成異常,它會起作用。但是你的回答肯定會滿足問題的要求。 – 2009-06-18 20:21:00

2

如果你想保持流處處處處處處處處處處處處處處處處處處處處處處處處處處處,避免分配大量的字節數組,這是很好的做法(例如,如果你打算髮布大文件),你仍然可以使用派生版本的WebClient來完成。這是一個示例代碼。

using (var client = new WebClientWithResponse()) 
{ 
    using (var stream = client.OpenWrite(myUrl)) 
    { 
     // open a huge local file and send it 
     using (var file = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) 
     { 
      file.CopyTo(stream); 
     } 
    } 

    // get response as an array of bytes. You'll need some encoding to convert to string, etc. 
    var bytes = client.Response; 
} 

這裏是定製的Web客戶端:

public class WebClientWithResponse : WebClient 
{ 
    // we will store the response here. We could store it elsewhere if needed. 
    // This presumes the response is not a huge array... 
    public byte[] Response { get; private set; } 

    protected override WebResponse GetWebResponse(WebRequest request) 
    { 
     var response = base.GetWebResponse(request); 
     var httpResponse = response as HttpWebResponse; 
     if (httpResponse != null) 
     { 
      using (var stream = httpResponse.GetResponseStream()) 
      { 
       using (var ms = new MemoryStream()) 
       { 
        stream.CopyTo(ms); 
        Response = ms.ToArray(); 
       } 
      } 
     } 
     return response; 
    } 
} 
相關問題