How to read a WebClient response after posting data?

删除回忆录丶 提交于 2019-12-22 02:22:31

问题


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?


回答1:


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

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)




回答2:


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.

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:

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


来源:https://stackoverflow.com/questions/1014935/how-to-read-a-webclient-response-after-posting-data

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!