Last updated on 2019-10-30
Working with web services has become standard practice today, and it always felt strange to me how much work it took me to call one. I was doing it wrong :-). I found the Unirest library, and my life has been happy ever since.
To show how simple it is, I wrote a short program that queries the StackExchange API for questions in the StackOverflow site:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.vainolo.examples.javahttpapiclient; | |
import com.mashape.unirest.http.HttpResponse; | |
import com.mashape.unirest.http.JsonNode; | |
import com.mashape.unirest.http.Unirest; | |
public class JavaHTTPAPIClient { | |
public void getQuestionsUsingUnirest() throws Exception { | |
HttpResponse<JsonNode> response = Unirest.get("https://api.stackexchange.com/2.2/questions"). | |
header("accept", "application/json"). | |
queryString("order","desc"). | |
queryString("sort", "creation"). | |
queryString("filter", "default"). | |
queryString("site", "stackoverflow"). | |
asJson(); | |
System.out.println(response.getBody().getObject().toString(2)); | |
} | |
public static void main(String args[]) throws Exception { | |
JavaHTTPAPIClient client = new JavaHTTPAPIClient(); | |
client.getQuestionsUsingUnirest(); | |
} | |
} |
This call invokes a GET
request to https://api.stackexchange.com/2.2/questions
that accepts JSON
, including transforming the response to a JSON
object that can be easily used later.
Pretty cool, uh? The world is finally going forward.
You can find this example in my examples repository. Enjoy
Hi, Can I use XML instead of Json? What are the changes required if I use xml?
Don’t think so. API is here: http://javadox.com/com.mashape.unirest/unirest-java/1.4.5/com/mashape/unirest/request/GetRequest.html