Click here to Skip to main content
14,773,285 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have my SendRequest method that returns HttpWebResponse class, I want to get the response as Json when I use it in my Get request method. How can I achieve this?

Here is my SendRequest method

private HttpWebResponse SendRequest(HttpWebRequest request, string queryParams, string token)
        {
            HttpWebResponse response = null;
            if(token != null)
            {
                request.Headers.Add("Authorization", "Bearer " + token);

            }

            request.ContentType = "application/json";

            try
            {
                
                response = (HttpWebResponse)request.GetResponse();
                
            }
            catch (WebException wex)
            {
                if (wex.Response == null)
                    throw new WebException(wex.StackTrace);

                using (var errorResponse = (HttpWebResponse)wex.Response)
                {
                    using (var reader = new StreamReader(errorResponse.GetResponseStream()))
                    {
                        throw new Exception(reader.ReadToEnd()); //expected error from JSON
                    }
                }
            }
            var responseVal = new StreamReader(stream: response.GetResponseStream()).ReadToEnd();

            return response;
        }



Here is GET Method

public HttpWebResponse IsGet(string baseURL, string basePath, string queryParams, string token)
       {
           var request = (HttpWebRequest)WebRequest.Create(baseURL+basePath+queryParams);
           request.Method = "GET";
          return SendRequest(request, queryParams, token);
       }



Here is my Test method

[Test]
public void GetUser()
{
    HttpWebResponse response  = client.IsGet(baseURL, "/User", null, token);
    //trying to get the Json response here....???

}


What I have tried:

I have tried to create a Response Handler class to convert it to Json but I get an error
"Newtonsoft.Json.JsonReaderException : Error reading JToken from JsonReader. Path '', line 0, position 0"
Stack Trace:
JToken.ReadFrom(JsonReader reader, JsonLoadSettings settings)
JToken.Parse(String json, JsonLoadSettings settings)
JToken.Parse(String json)


Here is the request Handler Class

public class ResponseHandler
   {
       public Stream unEncodedResponseStream;
       public StreamReader reader;
       public JContainer jsonResponseContainer;
       public HttpWebResponse responsePassedIn;
       public string responseAsJsonString;

       public Stream UnEncodeResponseStream()
       {
           // Unencode your response stream or, if it is not encoded, return it.
           var responseStream = responsePassedIn.GetResponseStream();
           if (responsePassedIn.ContentEncoding.ToLower().Contains("gzip"))
               unEncodedResponseStream = new GZipStream(responseStream, CompressionMode.Decompress);
           else if (responsePassedIn.ContentEncoding.ToLower().Contains("deflate"))
               unEncodedResponseStream = new DeflateStream(responseStream, CompressionMode.Decompress);
           else
               unEncodedResponseStream = responseStream;

           return unEncodedResponseStream;
       }

       public string ConvertResponseStreamToString(HttpWebResponse webResponse)
       {
           // Unencode Response Stream.
           responsePassedIn = webResponse;
           var responseStream = UnEncodeResponseStream();

           // Convert the response to a JSON string.
           reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
           return reader.ReadToEnd();
       }

       public JContainer ConvertResponseToJson(HttpWebResponse response)
       {
           string localString;

           if (response.ContentEncoding.Contains("application/xml"))
           {
               // Convert the escaped Stream into an XML document.
               ConfigXmlDocument xmlDocument = new ConfigXmlDocument();
               xmlDocument.LoadXml(ConvertResponseStreamToString(response));

               // Now convert the properly-escaped JSON for the response into a JContainer
               localString = JsonConvert.SerializeXmlNode(xmlDocument);
           }
           else
               localString = ConvertResponseStreamToString(response);

           return JToken.Parse(localString) as JContainer;
       }
   }
Posted
Updated 17-May-20 23:32pm

1 solution

The data returned by the source may not be JSON - as far as HttpWebResponse is concerned, it's just a stream of bytes, it includes little or no context beyond that.

So if Newtonsoft is returning an error "Error reading JToken from JsonReader. Path '', line 0, position 0" then you need to look closely at exactly what it beging returned, and processed.

The way to do that is to use either the debugger to view it live in your code, or to write it to a file for off-line examination.

If it looks like JSON, then feed it to a class creator as see what that generates: Json2CSharp[^] is the one I use.
Almost certainly, what you assume is JSON isn't JSON at all, or it's "packaged" in a way that you need to process the returned data yourself before passing it to a JSON reader.

But we can't do any of that for you!
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900