看代码:
using (var client = new WebClient())
{
using (var stream = client.OpenWrite("http://localhost/", "POST"))
{
stream.Write(post, 0, post.Length);
}
}
现在,我如何读取 HTTP 输出?
看起来您有一些byte[]
数据要发布;在这种情况下,我希望您会发现它更易于使用:
byte[] response = client.UploadData(address, post);
如果响应是文本,例如:
string s = client.Encoding.GetString(response);
(或您的选择Encoding
- 也许Encoding.UTF8
)
如果您想在任何地方保留流并避免分配大量字节数组,这是一种很好的做法(例如,如果您打算发布大文件),您仍然可以使用 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;
}
这是定制的WebClient:
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;
}
}