Unirest - HTTP Client

by GarciaPL on Saturday 14 March 2015

I am currently developing some application in Swing which does a lot of crazy things, but it also connects to backend system via REST interfaces to retrieve or send some XML's. At this moment I must to admit that one of the most powerful libraries used by me to serialize and deserialize XML is nothing else that XStream [1]. It is really worth of using. Very powerful and configurable. It deserves to be described in separate post.

Back to the topic, I was looking for some HTTP client request library which can help me to make some requests to server in approachable way. On the one hand we have HttpClient supplied by Apache in httpcomponents package [2]. We have also RestTemplate supplied by Spring team [3] and so on. But this time I found library called Unirest! [4].

You can make GET, POST, PUT, PATCH, DELETE, HEAD and OPTIONS requests in synchronous or asynchronous way, supports form parameters, file uploads, gzip, Basic Authentication, timeouts, proxy, responses in String or JSON.

In this post I would like to present two mainly used at this moment in previously mentioned application, approaches to REST interfaces using of course GET and POST methods. There also be used Basic Authentication.

Firstly let's create interface for those methods :

public interface mQubeQueries {
        List getPlayers(Integer serviceId, Date from, Date to) throws UnirestException, XStreamException;
        void sendResults(Integer serviceId, Integer stageId, List results) throws UnirestException, XStreamException;
}
GET

public class mQubeQueriesImpl implements mQubeQueries {
    private XStream xStream;

    public mQubeQueriesImpl() {
        this.xStream = new XStream();
        this.xStream.setMode(XStream.ID_REFERENCES);
    }

    @Override
    public List getPlayers(Integer serviceId, Date from, Date to) throws UnirestException, XStreamException {
        GetRequest response = Unirest.get("http://server.com/" + "get-players" + "/" + serviceId +
                "/" + new DateFormatter().formatQubeDateTimezone(from) +
                "/" + new DateFormatter().formatQubeDateTimezone(to)).basicAuth("login", "password");

        if (response.asString().getStatus() == 403) {
            throw new UnirestException("No authorized");
        }

        if (response.asString().getStatus() != 200) {
            throw new UnirestException("Unexpected response with code : " + response.asString().getStatus());
        }

        String body = response.asString().getBody();
        if (body == null) {
            throw new UnirestException("Response from server is null");
        } else {
            try {
                return (List) xStream.fromXML(body);
            } catch (Exception e) {
                throw new XStreamException(e.getMessage());
            }
        }
    }
}


POST

    @Override
    public void sendResults(Integer serviceId, Integer stageId, List results) throws UnirestException, XStreamException {
        List results = new ArrayList();
        for (Entrant entrant : results) {
            ResultDTO record = new ResultDTO();
            record.setDateCreated(new Date());
            results.add(record);
        }

        String xml = xStream.toXML(results);

        HttpResponse response = Unirest.post("http://server.com/" + "send-drawing-results" +
                "/" + serviceId + "/" + stageId).basicAuth("login", "password").
                header("Content-Type", "application/xml").body(xml).asString();

        if (response.getStatus() == 403) {
            throw new UnirestException("No authorized");
        }

        if (response.getStatus() != 204) {
            throw new UnirestException("Unexpected response with code " + response.getStatus());
        }
    }
References :
[1] XStream
[2] HC Apache
[3] Spring RestTemplate
[4] Unirest
[5] Pastebin Interface Source Code
[6] Pastebin GET Method Source Code
[7] Pastebin POST Method Source Code