C# 发布数据后如何读取 WebClient 响应?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1014935/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 05:35:11  来源:igfitidea点击:

How to read a WebClient response after posting data?

c#.netwebclient

提问by Jader Dias

Behold the code:

看代码:

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

Now, how do I read the HTTP output?

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

采纳答案by Marc Gravell

It looks like you have a byte[]of data to post; in which case I expect you'll find it easier to use:

看起来你有一个byte[]数据要发布;在这种情况下,我希望您会发现它更易于使用:

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

And if the response is text, something like:

如果响应是文本,则类似于:

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

(or your choice of Encoding- perhaps Encoding.UTF8)

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

回答by Simon Mourier

If you want to keep streams everywhere and avoid allocating huge arrays of bytes, which is good practise (for example, if you plan to post big files), you still can do it with a derived version of WebClient. Here is a sample code that does it.

如果您想在任何地方保留流并避免分配大量字节,这是一种很好的做法(例如,如果您计划发布大文件),您仍然可以使用 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;
}

And here is the customized WebClient:

这是定制的 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;
    }
}