Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting full response body from System.Net.WebRequest

I'm using System.Net.WebRequest to get info from some API. When I get an error, the response contains only the basic HttpStatusCode and message, and not the full error returned. For comparison, running the same post data and headers in a tool such as POSTMAN will return the full error from that API.

I'm wondering if there is some property or way I can get the full error response??

Here is the code i'm running:

public HttpStatusCode GetRestResponse(
    string verb,
    string requestUrl,
    string userName,
    string password,
    out string receiveContent,
    string postContent = null)
{
    var request = (HttpWebRequest)WebRequest.Create(requestUrl);
    request.Method = verb;

    if (!string.IsNullOrEmpty(userName))
    {
        string authInfo = string.Format("{0}:{1}", userName, password);
        authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
        request.Headers.Add("Authorization", "Basic " + authInfo);
    }

    if (!string.IsNullOrEmpty(postContent))
    {
        byte[] byteArray = Encoding.UTF8.GetBytes(postContent);
        request.ContentType = "application/json; charset=utf-8";
        request.ContentLength = byteArray.Length;
        var dataStream = request.GetRequestStream();
        dataStream.Write(byteArray, 0, byteArray.Length);
        dataStream.Close();
    }

    try
    {
        using (WebResponse response = request.GetResponse())
        {
            var responseStream = response.GetResponseStream();
            if (responseStream != null)
            {
                var reader = new StreamReader(responseStream);
                receiveContent = reader.ReadToEnd();
                reader.Close();

                return ((HttpWebResponse) response).StatusCode;
            }
        }
    }
    catch (Exception ex)
    {
        receiveContent = string.Format("{0}\n{1}\nposted content = \n{2}", ex, ex.Message, postContent);
        return HttpStatusCode.BadRequest;
    }

    receiveContent = null;
    return 0;
}

When I generate a request that presents me with an error, I get in the error message: The remote server returned an error: (400) Bad Request. and no InnerException, and nothing else I can benefit from out of the exception.

[Answer] @Rene pointed to the right direction and the proper response body can be acquired like this:

var reader = new StreamReader(ex.Response.GetResponseStream());
var content = reader.ReadToEnd();
like image 559
AlexD Avatar asked Aug 23 '15 13:08

AlexD


People also ask

What is System Net WebRequest?

WebRequest is the abstract base class for . NET's request/response model for accessing data from the Internet.

How do I reply to WebRequest?

The GetResponse method sends a request to an Internet resource and returns a WebResponse instance. If the request has already been initiated by a call to GetRequestStream, the GetResponse method completes the request and returns any response. The GetResponse method provides synchronous access to the WebResponse.

What is System Net WebException?

Net. WebException. The exception that is thrown when an error occurs while accessing the network through a pluggable protocol.


1 Answers

You're catching the generic exception so there is not much room for specific info.

You should catch the specialized exception that is thrown by the several webrequest classes, namely WebException

Your catch code could be like this:

catch (WebException e)
{
    var response = ((HttpWebResponse)e.Response);
    var someheader = response.Headers["X-API-ERROR"];
    // check header

    if (e.Status == WebExceptionStatus.ProtocolError)
    {
        // protocol errors find the statuscode in the Response
        // the enum statuscode can be cast to an int.
        int code = (int) ((HttpWebResponse)e.Response).StatusCode;
        string content;
        using(var reader = new StreamReader(ex.Response.GetResponseStream()))
        {
            content = reader.ReadToEnd();
        }
        // do what ever you want to store and return to your callers
    }
}

In the WebException instance you also have access to the Response send from the host, so you can reach anything that is being send to you.

like image 162
rene Avatar answered Sep 21 '22 04:09

rene