我控制两个网站,所以任何方法都可以。
必须有一个比以下更简单的方法:
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 :(得分: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.