2013-11-25 44 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

相关问题