Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplest way to make HTTP request in Spring

In my Spring web application I need to make an HTTP request to a non-RESTful API, and parse the response body back as a String (it's a single-dimension CSV list).

I've used RestTemplate before, but this isn't RESTful and doesn't map nicely on to classes. Whenever I implement something like this 'by hand' (eg using HttpClient) I invariably find out later that Spring has a utility class that makes things much simpler.

Is there anything in Spring that will do this job 'out of the box'?

like image 469
EngineerBetter_DJ Avatar asked Nov 01 '11 16:11

EngineerBetter_DJ


2 Answers

If you look at the source of RestTemplate you will find that internally it uses

java.net.URL

and

url.openConnection()

that is the standard way in Java to make HTTP calls, so you are safe to use that. If there would be a "HTTP client" utility in spring then the RestTemplate would use that too.

like image 178
Peter Szanto Avatar answered Sep 18 '22 00:09

Peter Szanto


I use the Spring Boot with Spring 4.3 Core inside and found a very simple way to make Http request and read responses by using OkHttpClient. Here is the code

Request request = new Request.Builder().method("PUT", "some your request body")
            .url(YOUR_URL)
            .build();
        OkHttpClient httpClient = new OkHttpClient();
        try
        {
            Response response = httpClient.newBuilder()
            .readTimeout(1, TimeUnit.SECONDS)
            .build()
            .newCall(request)
            .execute();
            if(response.isSuccessful())
            {
                // notification about succesful request
            }
            else
            {
                // notification about failure request
            }
        }
        catch (IOException e1)
        {
            // notification about other problems
        }
like image 37
Vitaly Vlasov Avatar answered Sep 19 '22 00:09

Vitaly Vlasov