将字节数组从一个站点发送到另一个站点(并返回)

时间:2013-11-25 22:58:13

标签: c# asp.net http post

我控制两个网站,所以任何方法都可以。

必须有一个比以下更简单的方法:

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();
}

不是吗?

(代码是请求方。响应者更简单。)

1 个答案:

答案 0 :(得分:1)

您可以使用WebClient来缩小代码。具体来说,UploadData方法:

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

..并下载:

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

您可以通过WebClient Headers属性添加所需的标题:

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