-1

i m new to API testing and i just want to know how can i able to read the response from request made in c#. i tried below.

for example i have a API url :- http://api.test.com/api/xxk/jjjj?limit=30

            HttpWebRequest request = WebRequest.Create("http://api.test.com/api/xxk/jjjj?limit=30") as HttpWebRequest;
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {

                var res = response;
            }

that is giving me response but i need to get all the Json response result and need to access the value for it.

When i check in debug mode for response i cant see all the response value. Also which oject will give me all values there? i'm sure i m doing something wrong but if anyone will help me to find out that would be great .

vic
  • 217
  • 1
  • 7
  • 18

1 Answers1

2

You could check https://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.getresponse(v=vs.110).aspx for a detailed explanation on how to get the httpBody of your response. After you get your response with .getResponse() you can get the response Stream and read the content from it in a variable.

as stated in the link article:

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create (args[0]);
        HttpWebResponse response = (HttpWebResponse)request.GetResponse ();

        Console.WriteLine ("Content length is {0}", response.ContentLength);
        Console.WriteLine ("Content type is {0}", response.ContentType);

        // Get the stream associated with the response.
        Stream receiveStream = response.GetResponseStream ();

        // Pipes the stream to a higher level stream reader with the required encoding format. 
        StreamReader readStream = new StreamReader (receiveStream, Encoding.UTF8);

        Console.WriteLine ("Response stream received.");
        Console.WriteLine (readStream.ReadToEnd ());
        response.Close ();
        readStream.Close ();

The output will be:

/*
The output from this example will vary depending on the value passed into Main 
but will be similar to the following:

Content length is 1542
Content type is text/html; charset=utf-8
Response stream received.
<html>
...
</html>

*/

With :

var res = readStream.ReadToEnd();

You will get the json body in a string representation. After this you can parse it using a json parser like Newtonsoft.JSON.

I hope this answers your question at least 70%. I think there are ways to write an API that parses the JSON body automatically (at least with the new net core (mvc vnext)). I have to remember the method exactly..

Daniel Colceag
  • 190
  • 1
  • 3
  • 15