Wednesday, 1 February 2017

Api testing : Get

Simple GetApi code:

Maven dependency:
<!--For Http Get/Post/ect we need HTTP client libs :: http://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.6</version>
</dependency>



<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20160810</version>
</dependency>


import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.testng.Assert;

public class TestGet {

public static void main(String[] args) {

String url = "https://httpbin.org/get";
HttpResponse response = null;

HttpClientBuilder builder = HttpClientBuilder.create();
HttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager();
builder.setConnectionManager(connectionManager);
HttpClient httpclient = builder.build();
RequestConfig requestConfig = RequestConfig.custom()
/*
* connectionRequestTimeout happens when you have a pool of
* connections and they are all busy, not allowing the
* connection manager to give you one connection to make the
* request.
*/
.setConnectionRequestTimeout(30000)
/*
* connectTimeout happens when establishing the connection. For
* instance while doing the tcp handshake.
*/
.setConnectTimeout(30000)
/*
* socketTimeout: is the timeout while waiting for data. Usually
* happens when your server is slow
*/
.setSocketTimeout(30000).build();
try {
HttpGet httpget = new HttpGet(url);
httpget.setConfig(requestConfig);
response = httpclient.execute(httpget);
String responseBody = EntityUtils.toString(response.getEntity());
JSONObject jsonObj = new JSONObject(responseBody);
System.out.println(jsonObj.get("origin"));
//Assert.assertTrue(response.getStatusLine().getStatusCode() == 200);
} catch (IOException ex) {

}

}

}

No comments:

Post a Comment