In our previous post, we wrote about parsing JSON using Java and GSON library. Moving further, in this article we will look at how to use classes in java.net package to invoke a RESTful Web Service and then parse the JSON response using GSON library. For this we make use of the Twitter REST API and more specifically statuses/user_timeline API. A bit about the API:
also read:
- Java Tutorials
- Java EE Tutorials
- Design Patterns Tutorials
- Java File IO Tutorials
GET status/user_timeline: Returns the 20 most recent statuses posted by the authenticating user. It is also possible to request another user’s timeline by using the screen_name or user_id parameter. The other users timeline will only be visible if they are not protected, or if the authenticating user’s follow request was accepted by the protected user.
The resource URL is: http://api.twitter.com/1/statuses/user_timeline.format
The API returns lot of data, but we are interested in only the status text and the created date. Keeping that in mind, our model class will be:
class Tweet{ public String text; public String created_at; public String toString(){ return "Posted "+text+" at "+created_at; } }
The example can be divided into:
- Take screen name input from the user and construct the URL for the API which we call as the fetchURL.
- Use URLConnection class and its connect() and getInputSteam() APIs to connect to the fetchURL and then obtain the input stream.
- The input stream obtained above is used to construct the JsonReader object( from the GSON library).
- Then parse the JSON as explained here.
Invoking the REST API:
String fetchUrl = "http://api.twitter.com/1/statuses/user_timeline.json?screen_name="; //this.screenName is obtained as a user input fetchUrl = fetchUrl+this.screenName; URLConnection urlConnection = new URL(fetchUrl).openConnection(); urlConnection.connect();
One can see that to invoke a REST web service, we need not have to use any other APIs then then ones provided in the java.net package. There are a lot of libraries available for invoking and creating REST APIs. But in this example we stick with java.net package. This simplicity is due to the fact that REST APIs are based on top of HTTP related protocols and uses GET, POST, PUT, DELETE and other methods supported by HTTP.
Parsing the JSON response:
JsonReader reader = new JsonReader( new InputStreamReader(urlConnection.getInputStream())); JsonParser parser = new JsonParser(); JsonElement rootElement = parser.parse(reader); JsonArray tweetsJson = rootElement.getAsJsonArray();
Populate the required model instances and add them to the List of tweets (or List<Tweet>).
List timeline = new ArrayList(); Gson myGson = new Gson(); for ( JsonElement tweetElement : tweetsJson){ Tweet myTweet = myGson.fromJson(tweetElement, Tweet.class); timeline.add(myTweet); }
Read here for details on parsing the JSON using Java and GSON API.
Here is the complete code:
import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonParser; import com.google.gson.stream.JsonReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class RestfulDemo { public static void main(String [] args) throws IOException{ Scanner commandlineReader = new Scanner(System.in); System.out.println("Enter the screen name"); String screenName = commandlineReader.nextLine(); TwitterTimeline myTimeline = new TwitterTimeline(screenName); myTimeline.fetchTimeline(); for ( Tweet myTweet : myTimeline.timeline){ System.out.println(myTweet); } } } class TwitterTimeline { public String screenName; public List timeline; private String fetchUrl = "http://api.twitter.com/1/statuses/user_timeline.json?screen_name="; TwitterTimeline( String screenName) { this.screenName = screenName; } public void fetchTimeline() throws IOException { fetchUrl = fetchUrl+this.screenName; URLConnection urlConnection = new URL(fetchUrl).openConnection(); urlConnection.connect(); JsonReader reader = new JsonReader( new InputStreamReader(urlConnection.getInputStream())); JsonParser parser = new JsonParser(); JsonElement rootElement = parser.parse(reader); JsonArray tweetsJson = rootElement.getAsJsonArray(); timeline = new ArrayList(); Gson myGson = new Gson(); for ( JsonElement tweetElement : tweetsJson){ Tweet myTweet = myGson.fromJson(tweetElement, Tweet.class); timeline.add(myTweet); } } } /* * Model class for a Tweet */ class Tweet { public String text; public String created_at; public String toString(){ return "Posted "+text+" at "+created_at; } }
Note: Make sure you have GSON library in the classpath.
Also if you have any issues while trying out this example, do drop a comment here and we will get back to you at the earliest.