2013-11-25 43 views
1

我控制兩個站點,所以任何方法都可以。從一個站點發送字節數組到另一個(並返回)

必須有一個更簡單的方法,然後執行以下操作:

byte[] result; 
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://blahblah.com/blah.ashx"); 
byte[] inputToSend = new byte[] { 1, 2, 3 }; 
request.Method = "POST"; 
request.ContentType = "image/jpeg"; 
request.Timeout = 30 * 1000; 
request.ContentLength = inputToSend.Length; 
using (Stream stream = request.GetRequestStream()) 
    stream.Write(inputToSend, 0, inputToSend.Length); 
request.Headers.Add("blah", "more blah");//This is for authentication. 
WebResponse r = request.GetResponse(); 
using (MemoryStream ms = new MemoryStream()) 
{ 
    r.GetResponseStream().CopyTo(ms); 
    result = ms.ToArray(); 
} 

不是這樣呢?

(代碼是請求側,響應更簡單。)

+0

可能重複[如何在發佈數據後讀取WebClient響應? (.NET)](http://stackoverflow.com/questions/1014935/how-to-read-a-webclient-response-after-posting-data-net) –

回答

1

你可能使用WebClient使代碼更小。具體來說,UploadData方法:

using (var wc = new WebClient()) { 
    wc.UploadData(yourUrl, inputToSend); 
} 

..和下載:

using (var wc = new WebClient()) { 
    var receivedData = wc.DownloadData(yourUri); 
} 

您可以添加通過Web客戶端需要Headers財產的任何標題:中

wc.Headers.Add("blah", "blah"); // your auth stuff here. 
+0

謝謝。那看起來很有希望但是有沒有辦法用WebClient請求+響應? (接收到的數據是對發送的數據的響應) – ispiro

+0

OK。沒關係 - 我發現這個http://stackoverflow.com/a/1014944/939213顯示'UploadData'返回一個響應。 – ispiro

相關問題