Created
April 30, 2012 14:57
-
-
Save sanaulla123/2559019 to your computer and use it in GitHub Desktop.
Using REST api in Java
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
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; | |
/** | |
* Created by IntelliJ IDEA. | |
* User: sanaulla | |
* Date: 30/4/12 | |
* Time: 7:06 PM | |
* To change this template use File | Settings | File Templates. | |
*/ | |
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<Tweet> 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<Tweet>(); | |
Gson myGson = new Gson(); | |
for ( JsonElement tweetElement : tweetsJson){ | |
Tweet myTweet = myGson.fromJson(tweetElement, Tweet.class); | |
timeline.add(myTweet); | |
} | |
} | |
} | |
class Tweet{ | |
public String text; | |
public String created_at; | |
public String toString(){ | |
return "Posted "+text+" at "+created_at; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment