When we run the TweetDemo servlet, the user's friends timeline is displayed in an HTML formatted manner as the output
package com.examples.pcq;
import java.io.*; import java.util.List; import javax.servlet.*; import javax.servlet.http.*; import twitter4j.*;
public class TweetDemo extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet { public TweetDemo() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {
String user=null; String text=null; Twitter twitter = new Twitter("username", "password"); Status status = twitter.updateStatus("This is PCQuest demo for Twitter4J"); List statuses = twitter.getFriendsTimeline();
PrintWriter outputToBrowser = new PrintWriter(response.getOutputStream()); response.setContentType("text/html"); String htmlPage = "Twitter Update and Friends Timeline"; htmlPage += ""; htmlPage += "
ter>Showing friends timeline:-"; for(int i=0; i < statuses.size() ; i++) { Status status1 = (Status)statuses.get(i); user = status1.getUser().getName(); text = status1.getText(); htmlPage += ""+user+":"; htmlPage += ""+text+""; htmlPage += ""; } outputToBrowser.println(htmlPage); String htmlPage2 = ""; htmlPage2 += "
Formatting the Timeline The getFriendsTimeline() method returns the list of statuses, and we can iterate through those statuses list to get each status's user name and the text message of the status.
Using response.getWriter() we can display the output as text on the browser, but not in a formatted style. To present the output in as a HTML page we use the PrintWriter class of the java.io package.
This class implements all of the print methods found in PrintStream, and is used for print formatted representations for a text output stream. The PrintWriter will stream the output through the getOutputStream() method of the ResponseServlet. We will set the content type of the response being sent to the client as text/html through the ResponseServlet's setContentType() method.
Conclusion Thus we have created a servlet based application that can send user updates to twitter and fetch user's friends updates back. Though in our example we have hard-coded the TwitterID and password, but while creating an application you can pass the user's Twitter ID and password through a JSP form to the servlet.
Get most out of your technology infrastructure investments with Dell
About CIOL | Media Kit | Site Map | Contact Us | Help | Write to us | Jobs@CyberMedia | Privacy Policy
Copyright © CyberMedia India Online Ltd. All rights reserved. Usage of content from web site is subject to Terms and Conditions.