zondag 31 januari 2016

Apache HttpClient connect

Introduction

 As sometimes needed you want one service to communicate with the other without interference of the frontend. One of the ways to do that is to setup a connection through the apache httpClient. In our project we allready did that but with an old version of te HttpClient. Therefore we needed to upgrade to the latest version. At this point in time it is 4.5.1. The only downside of this client is, that it is still not upgraded to HTTP 2.0. read the specs here. But we did it anyway in the hope that the coming version would use the HTTP 2.0 specifications. 

The solutution

This solution is not giving you the whole shabang  but it gives you a good idea howto setup a basic configuration that works and will help you to setup through a proxy or not.

//The maven part:
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.1</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpcore</artifactId>
    <version>4.4.4</version>
</dependency>


//If you in need of a proxy set it up like this with ofcourse the right adress and 
//port.
HttpHost proxy = new HttpHost("proxy", 8080, "http");
// Configure the request with timeouts and in this case a proxy. 
//If you don't need a proxy you can leave that particular part out 
RequestConfig config = RequestConfig.custom()
        .setConnectionRequestTimeout(30000)
        .setSocketTimeout(30000)
        .setProxy(proxy)
        .build();
//Instead of using the HttpMethod in the old version we now 
//should use the HttpGet or the HttpPost HttpGet httpget = 
new HttpGet("http://yourservice/getEverything");
httpget.setConfig(config);
//This is one of the ways to setup a HttpClient.
//there are many more ways as you will find in these examples. 
HttpClient client = HttpClientBuilder.create()
        .build();
// retrieving the response as HttpResponse and printout
//the http statusHttpResponse response = client.execute(httpget);
System.out.println(response.getStatusLine());


Conclusion

It is not so hard to set this up once you have an idea of what you need to do. I been searching the internet for a some examples. The sad story of this search was that there a lot of old examples out there. I only hope that this library is soon updated to http 2.0.

Geen opmerkingen:

Een reactie posten