Web Services Testing

How to perform Web Services Testing using HTTPClient

Web Services Testing

Web Services Testing

Download – HTTP Client  from below link and extract the zip file and add all jars into project

http://hc.apache.org/downloads.cgi 

Add

JSON Jar to read json format.

 

Web Services Testing

 

Before moving to test Web Services Testing, please go through the basics of Web Service.

Please check below article from W3School

Intro to WebServices

We will be testing Web Services in two ways

1- Using JSON File.

2-Using XML File.

 

How to verify HTTP Response for Web Service Testing

First we will verify HTTP response using response code below

Status codes

Most status codes which frequently used

200- Ok

404- Page not found

401- Unauthorized

 

Below is the piece of code which will verify HTTP Response

public static void testStatusCode(String restURL) throws ClientProtocolException, IOException

{
// Create Object and pass the url
HttpUriRequest request = new HttpGet(restURL);

// send the response or execute the request
HttpResponse httpResponse = HttpClientBuilder.create().build().execute(request);

// Verify the response code is equal to 200
Assert.assertEquals(httpResponse.getStatusLine().getStatusCode(),HttpStatus.SC_OK);
}

 

How to verify the response Content type for Web Services testing

public static void testMimeType(String restURL, String expectedMimeType) throws ClientProtocolException, IOException {

// Create object of HTTP request
HttpUriRequest request = new HttpGet(restURL);

// Send the request 
HttpResponse httpResponse = HttpClientBuilder.create().build().execute(request);

// Verify the response type 
Assert.assertEquals(expectedMimeType,ContentType.getOrDefault(httpResponse.getEntity()).getMimeType());
}

 

How to extract response from XML File for Web Services Testing

public static void testContent(String restURL, String element, String expectedValue) throws ClientProtocolException, IOException, SAXException, ParserConfigurationException {

// Parse the URL
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(restURL);

// Get the element from response using element tag name
NodeList nodelist = doc.getElementsByTagName(element);

// Verify the response content using Assert
Assert.assertEquals(expectedValue,nodelist.item(0).getTextContent()); 
}

 

How to extract response from JSON File for Web Services Testing

public static void testContentJSON(String restURL, String element, String expectedValue) throws ClientProtocolException, IOException, SAXException, ParserConfigurationException, JSONException {

// Create request object
HttpUriRequest request = new HttpGet(restURL);

// send response or execute query
HttpResponse httpResponse = HttpClientBuilder.create().build().execute(request);

// Convert the response to a String format
String result = EntityUtils.toString(httpResponse.getEntity());

// Convert the result as a String to a JSON object
JSONObject jo = new JSONObject(result);

// Verify content
Assert.assertEquals(expectedValue, jo.getString(element));

}

 

Full program for Web Services Testing

import java.io.IOException;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Assert;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class RESTTester {

public static void main (String args[]) {

// This is request which we are sending to server 
String restURL_XML = "http://parabank.parasoft.com/parabank/services/bank/customers/12212/";

// sending request and we are passing parameter in url itself
String restURL_JSON = "http://api.openweathermap.org/data/2.5/weather?q=Amsterdam";

try {

testStatusCode(restURL_XML);
testStatusCode(restURL_JSON);
testMimeType(restURL_XML,"application/xml");
testMimeType(restURL_JSON,"application/json");
testContent(restURL_XML,"lastName","Smith");
testContentJSON(restURL_JSON,"name","Amsterdam");

} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public static void testStatusCode(String restURL) throws ClientProtocolException, IOException {

HttpUriRequest request = new HttpGet(restURL);
HttpResponse httpResponse = HttpClientBuilder.create().build().execute(request);

Assert.assertEquals(httpResponse.getStatusLine().getStatusCode(),HttpStatus.SC_OK);
}

public static void testMimeType(String restURL, String expectedMimeType) throws ClientProtocolException, IOException {

HttpUriRequest request = new HttpGet(restURL);
HttpResponse httpResponse = HttpClientBuilder.create().build().execute(request);

Assert.assertEquals(expectedMimeType,ContentType.getOrDefault(httpResponse.getEntity()).getMimeType());
}

public static void testContent(String restURL, String element, String expectedValue) throws ClientProtocolException, IOException, SAXException, ParserConfigurationException {


Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(restURL);
NodeList nodelist = doc.getElementsByTagName(element);

Assert.assertEquals(expectedValue,nodelist.item(0).getTextContent()); 
}

public static void testContentJSON(String restURL, String element, String expectedValue) throws ClientProtocolException, IOException, SAXException, ParserConfigurationException, JSONException {

HttpUriRequest request = new HttpGet(restURL);
HttpResponse httpResponse = HttpClientBuilder.create().build().execute(request);

// Convert the response to a String format
String result = EntityUtils.toString(httpResponse.getEntity());

// Convert the result as a String to a JSON object
JSONObject jo = new JSONObject(result);

Assert.assertEquals(expectedValue, jo.getString(element));

}

}

 

If you find this useful then please share with friends. Comment below if any doubt, suggestion or feedback.

Thanks for visiting my blog. Have a nice day 🙂

For More updates Learn Automation page

For any query join Selenium group- Selenium Group

 

 

author-avatar

About Mukesh Otwani

I am Mukesh Otwani working professional in a beautiful city Bangalore India. I completed by BE from RGPV university Bhopal. I have passion towards automation testing since couple of years I started with Selenium then I got chance to work with other tools like Maven, Ant, Git, GitHub, Jenkins, Sikuli, Selenium Builder etc.

25 thoughts on “How to perform Web Services Testing using HTTPClient

  1. Vamshi G says:

    Simple and easily explained. Thank you

    1. Thanks Vamshi…:)

  2. Preetish Kumar Mahato says:

    hi mukesh can u make a video for this tutorial… It will be easy to understand…

  3. Fayaz says:

    Hi Mukesh,

    Do we have any api where we can integrate wsdl and generate request using Java and Pass parameters dynamically for the same service.

    1. Hi Fayaz,

      Yes i have to cover this will cover soon.

  4. Hi Mukesh can you plz provide video for this web services testing actually by looking at code i am little bit confused. Please do the needful for me.

    1. Yes will upload soon.

  5. kanchana says:

    Thank you mukesh ji. The code is very helpful. But if you give video explanation, it will be very beneficial for beginner levels. Hope Waiting the for the videos on Api testing.

    1. Hi Kanchana,

      Yes Hope above code worked for you. I will try to create video on this soon and will update.

  6. Abhishek says:

    HEy… I want to develop a java famework to test rest apis. Do you have any course for this. I need it as a part of one project in my comapny

    1. Hi Abhishek,

      No as of now only Selenium course is in place.

  7. nandini says:

    Hi Mukesh,

    The blog is very good & informative.

    I am at beginner level,I understood code & flow mentioned in this blog however it would be helpful if you could post the outpost as well

    1. Hi Nandini,

      sure will do that

  8. cypherjobin says:

    Dear Mukesh,
    Thanks a lot for the introduction to the httpclient and the httpcore.

    looks like there are slight modification is already happened with the way we need to access the JSON API => http://openweathermap.org/ . They have introduced the appid (session id) to establish the connection and then invoke their REST service. The call without the session id is ending with the 403 error.

    However the explanation and the code are really good to deep dive in to the API consumption. I can now play around with the XMLs and JSONs

    Thanks again for the explanation.

    Best Regards
    Jobin

    1. Thanks Jobin will update the content soon.

  9. Ranjit says:

    it’s good

  10. amit j says:

    Very information. Thanks Mukesh.

    1. Thank you Amit keep visiting 🙂

  11. venu says:

    nice work on ws automation and keep doing great work. appreciate if you can upload Soap WS automation using java

    1. Hi Venu,

      Thank you I have uploaded 3 videos on SOAP UI. Hope you like it.

  12. Ramani says:

    Hi Mukesh, this blog is useful. If you can upload a video on “How to perform Web Services Testing using HTTPClient” that would be great!

    1. Hi Ramani,

      Thank you keep visiting.

      Yes I will upload soon.

  13. haritha says:

    thank u .information is useful me good explanation

    1. Thank you Haritha 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.