Creare un client HTTP in Java con Unirest

Mattepuffo's logo
Creare un client HTTP in Java con Unirest

Creare un client HTTP in Java con Unirest

Unirest è un libreria per creare richieste HTTP in maniera molto semplice e veloce.

E' disponibile per diversi linguaggi, ed oggi vedremo un esempio con Java.

Se usate Maven, aggiungete questa dipendenza al vostro pom.xml:

        <dependency>
            <groupId>com.mashape.unirest</groupId>
            <artifactId>unirest-java</artifactId>
            <version>1.4.9</version>
        </dependency>

A questo punto vediamo un esempio di richiesta GET usando il solito httpbin.org:

import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import org.json.JSONObject;

public class Main {

    public static void main(String[] args) {
        try {
            HttpResponse jsonResponse = Unirest.get("https://httpbin.org/get")
                    .asJson();
            JSONObject myObj = jsonResponse.getBody().getObject();
            System.out.println(myObj);
        } catch (UnirestException ex) {
            System.out.println(ex.getMessage());
        }
    }

}

Qui ho aggiunto anche il parsing del JSON, che potete fare in diversi modi ovviamente.

Possiamo anche usare i metodi asincroni:

public class Main {

    public static void main(String[] args) {
        Future jsonResponse = Unirest.get("https://httpbin.org/get")
                .asJsonAsync(new Callback() {
                    @Override
                    public void completed(HttpResponse hr) {
                        JSONObject myObj = hr.getBody().getObject();
                        System.out.println(myObj);
                    }

                    @Override
                    public void failed(UnirestException ue) {
                    }

                    @Override
                    public void cancelled() {
                    }
                });
    }

}

Enjoy!


Condividi

Commentami!