如何在发布数据后阅读WebClient响应?

时间:2009-06-18 20:12:05

标签: c# .net webclient

看看代码:

using (var client = new WebClient())
{
    using (var stream = client.OpenWrite("http://localhost/", "POST"))
    {
        stream.Write(post, 0, post.Length);
    }
}

现在,我如何阅读HTTP输出?

2 个答案:

答案 0 :(得分:22)

您似乎要发布byte[]个数据;在这种情况下,我希望你会发现它更容易使用:

byte[] response = client.UploadData(address, post);

如果回复是文本,则类似:

string s = client.Encoding.GetString(response);

(或您选择Encoding - 或许Encoding.UTF8

答案 1 :(得分:5)

如果你想在各处保留数据流并避免分配庞大的字节数组,这是一种很好的做法(例如,如果你计划发布大文件),你仍然可以使用派生版本的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;
    }
}