22

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?

Jader Dias
  • 88,211
  • 155
  • 421
  • 625

2 Answers2

31

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)

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • It would work, if I was not trying to read an HTTP 500 response, which turns to be an exception. But your answer surely fulfills the requirements of the question. – Jader Dias Jun 18 '09 at 20:21
  • You may want to clarify the question then; it may involve using HttpWebRequest... – Marc Gravell Jun 18 '09 at 20:27
  • Question continued at http://stackoverflow.com/questions/1015020/how-to-read-an-asp-net-internal-server-error-description-with-net – Jader Dias Jun 18 '09 at 20:28
  • 3
    You didn't answer the question :( – Mark Nov 17 '15 at 21:08
  • @MarcGravell Can you believe that UploadData methods wraps the whole file upload into multipart which is not required in this place and the Ops use the method which is more appreciated in that case. – Tomas Dec 07 '18 at 10:16
12

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;
    }
}
Simon Mourier
  • 132,049
  • 21
  • 248
  • 298