DEV Community

Cover image for A simple guide to Java http calls
tharos70
tharos70

Posted on • Updated on

A simple guide to Java http calls

Java http calls

Introduction

When it comes to consume an api with Java there are several options. One of my fovourite is Square's OkHttp.
It is a well known, full feature and highly customizable library which is moreover very easy to deal with. I noticed, in my daily job, that most of the times I have to deal with problems which force me to change my approach in calling APIs/Urls. That's why I decided to write a few recipe classes in order to organize my job when it comes to this topic.

The OkHttpClient API documentation states very clear that:

OkHttp performs best when you create a single OkHttpClient instance and reuse it for all of your HTTP calls. This is because each client holds its own connection pool and thread pools. Reusing connections and threads reduces latency and saves memory. Conversely, creating a client for each request wastes resources on idle pools.

In order to do this I set up an OkHttpClientInstanceHolder class so that in every call I need I can relate to the correct instance.

Why do we need different instances? Beacause we may want to have different flavoured http clients (ex. proxy enabled, with or without ssl channel checks, with or without a timeout handling, etc.)

Here are some of the HTTP request examples available in the repo:

GET

  • Simple GET Call: Performs a simple http GET call to the specified url with the specified query parameter.

  • Simple Get Call Timeout Aware: Performs a simple http GET call to the specified url with the specified query parameter with a specified timeout expressed in millisecond. When the timeout occurs, the call will be canceled.

  • Simple Unsafe GET Call: Performs a simple unsafe http GET call to the specified url with the specified query parameter with a specified timeout expressed in millisecond. When the timeout occurs, the call will be canceled. It is unsafe beacause in case of an https url call, the certificates chain will not be checked. It is not a recommended usage, but sometimes it may be useful for troubleshooting purpose.

  • Simple Async GET Call: Performs a simple asyncronous http GET call to the specified url.

POST

  • Simple POST Call: Performs a simple http POST call to the specified url with the specified json payload.

PUT

  • Simple PUT Call: Performs a simple http PUT call to the specified url with the specified json payload.

DELETE

  • Simple DELETE Call: Performs a simple http DELETE call to the specified url.

A complete list of the available sample calls can be found in the readme of the repo.

Please feel free to fork and submit you CR.

Here's the repo link: https://github.com/tharos70/http-client-samples.

I hope you like it!

Top comments (0)