Making Asynchronous Http Request using Dispatch

Dispatch is a library for asynchronous HTTP interaction. It allows us to make asynchronous Http request to the url. If there is a REST API, and you want to hit it from your code, its the thing that you are looking for.

For getting started, you have to add its dependency inside the build.sbt

DispatcherDependencies

Now you are good to go to use them inside your project.

Making HTTP Calls.

We’ll start with a very simple request.

Request

Here we define 5 seconds maximum to fetch the response from the API, if the response is not returned we get a TimeoutException

If we do not want to specify the wait time, and allow it to wait till the response comes. We can easily do that by using
[[scala.concurrent.duration.Duration.Inf Duration.Inf]] for unbounded waiting.

Making HTTPS Requests and Configuring the HttpMethods.

We can also define HTTPS request by defining

URL secure

But this does not solve the whole problem, and if the security protocols are of the TLSv1.2 , TLSv1.1, TLSv1 then we have to enable these protocols or else it will give us a handshake_failure.

We can solve this issue by configuring the HTTP.

RequestSSl

Having defined a request endpoint using either url, or host and the path-appending verb, you may now wish to change the HTTP method from its default of GET.

While configuring the Http remember to define it as lazy because while using the Http configure somehow it fails to shutdown the already open connection and gives a warning of HashedWheelTimer instances which ultimately results in the System going out of memory if your rest calls are too heavy.

We can easily perform it by defining HttpMethods, and you can easily see it from here.

1 thought on “Making Asynchronous Http Request using Dispatch

Leave a Reply

%d bloggers like this: