반응형
twitter API 연동을 하기 위해서는 https://dev.twitter.com MyApplication 에서 사용해야할 App을 등록한다.
필요한 Token을 얻을수 있다.
use library : http://twitter4j.org
API URL : http://twitter4j.org/javadoc/index.html
reference site :
1. Twitter.java
package com.test.java.social.twitter; import static com.sigongmedia.wbs.sbms.common.utils.StringUtils.*; import javax.servlet.http.HttpServletRequest; import twitter4j.IDs; import twitter4j.Paging; import twitter4j.ResponseList; import twitter4j.Status; import twitter4j.Twitter; import twitter4j.TwitterException; import twitter4j.TwitterFactory; import twitter4j.auth.AccessToken; import twitter4j.auth.RequestToken; import com.sigongmedia.wbs.sbms.common.log.SBMSLog; /** * <pre> * Class Name : TwitterClient3.java.java * Description : * Modification Information * * 수정일 수정자 수정내용 * ──────────── ───────── ─────────────────────────────── * 2013. 4. 15. skan 최초생성 * </pre> * * @author skan * @since 2013. 4. 15. * @version * * Copyright (C) 2011 by SIGONGMEDIA All right reserved. */ public class TwitterClient3 extends SBMSLog implements TwittweClientImpl{ public TwitterClient3() { super(); System. out.println("TwitterClient" ); } Twitter twitter; RequestToken requestToken = null ; AccessToken accessToken = null ; final String CONSUMER_KEY = "발급 받은 consumer key"; final String CONSUMER_SECRET = "발급 받은 consumer secret" ; /** * Twitter 계정으로 Sign in * @return */ public RequestToken getRequestToken() { twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer(CONSUMER_KEY , CONSUMER_SECRET ); requestToken = null ; try { requestToken = twitter .getOAuthRequestToken(); } catch (TwitterException te) { te.printStackTrace(); } System. out.println("1. TwitterClient.getRequestToken: " ); System. out.println("1.1 Token: " +requestToken .getToken() + " "); System. out.println("1.2 TokenSecret: "+requestToken.getTokenSecret() + " "); System. out.println("1.3 getAuthorizationURL: " + requestToken.getAuthorizationURL()); return requestToken ; } /** * AccessToken 얻기 * @param oauthToken * @param oauth_verifier * @param requestToken * @param request 필요한 경우에 따라 request 의 session 의것으로 사용 한다. * @return */ public AccessToken getAccessToken(String oauthToken, String oauth_verifier, RequestToken requestToken , HttpServletRequest request) { twitter = new TwitterFactory().getInstance(); com.test.java.social.twitter.Twitter<String> twitterDTO = new com.test.java.social.twitter.Twitter<String>(); twitterDTO.setCONSUMER_KEY( CONSUMER_KEY); twitterDTO.setCONSUMER_SECRET( CONSUMER_SECRET); twitter.setOAuthConsumer(CONSUMER_KEY , CONSUMER_SECRET ); System. out.println("TwitterClient.getAccessToken: " ); if(strIsNull(oauthToken)){ logger.info("get token ::" + requestToken.getToken()); if(requestToken.getToken().equals(oauthToken)) { try { System. out.print("2. requestToken: " ); System. out.println("2.1 getToken :" + requestToken.getToken() + " " ); System. out.println("2.2 TokenSecret :" + requestToken.getTokenSecret()); accessToken = twitter.getOAuthAccessToken(requestToken , oauth_verifier); twitter.setOAuthAccessToken(accessToken ); this.storeAccessToken(twitter .verifyCredentials().getId(), accessToken , request); } catch(TwitterException te) { te.printStackTrace(); } } else { System. out.println("oauth_token error" ); } } return accessToken ; } /** * AccessToken 저장 * * AccessToken 을 취득한 이후는 RequestToken 는 필요치 않습니다. 다음부터는 consumer key/secret 와 AccessToken 만으로 사용자계정에 접근 가능합니다. * @param userId * @param accessToken */ public void storeAccessToken(long userId , AccessToken accessToken, HttpServletRequest request){ //TODO :: SAVE try { request.getSession().setAttribute( "SESSION_ACCESS_TOKEN", accessToken); } catch (Exception e) { e.printStackTrace(); } } /** * 저장된 AccessToken 인스턴스 얻기 * @param token * @param tokenSecret * @return * @throws Exception */ public AccessToken getAccessToken(String token, String tokenSecret) throws Exception { try { twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer(CONSUMER_KEY , CONSUMER_SECRET); accessToken = new AccessToken(token, tokenSecret); twitter.setOAuthAccessToken(accessToken ); } catch (Exception e) { e.printStackTrace(); } return accessToken ; } /** * */ public void printStatuses() { ResponseList<Status> statuses; Paging page = new Paging(); page.count(20); page.setPage(1); try { statuses = twitter.getHomeTimeline(page); for (Status status : statuses) { // status.getId() // System.out.println(status.getUser().getScreenName() + ":" + status.getText()); // status.getUser().getScreenName() // status.getUser().getURL() // status.getText() // status.getCreatedAt() // status.getUser().getProfileImageURL() // status.getSource() } } catch (TwitterException te) { //te.printStackTrace(); } } /** * tweet update * @param message */ public void update(String message) { Status status = null; try { //status = twitter.updateStatus("http://ischooldev.sigongmedia.com/sbms/user/editor/EditorPage.do Please enter your text it is... ㄷㅈㄱㅂㅁㅇas d"); //status = twitter.updateStatus("죄송합니다. 이 글은 아직 한국어로 지원되지 않습니다."); System. out.println(message); status = twitter.updateStatus(message); } catch (TwitterException e) { e.printStackTrace(); } } /** * 친구목록 * @throws TwitterException */ public void friendsIds() throws TwitterException{ IDs ids = twitter.getFriendsIDs(10); long[] id_name = ids.getIDs(); for (int i = 0; i < id_name.length; i++) { System. out.println(twitter .showUser(id_name[i]).getName()); System. out.println(id_name[i]); } } } |
2. twitterSignin.jsp
<%@ page session="true" language="java" contentType= "text/html; charset=EUC-KR" pageEncoding="EUC-KR" %> <%@page import="com.test.java.social.twitter.TwitterClient3" %> <%@page import="twitter4j.auth.RequestToken" %> <!DOCTYPE html "> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=EUC-KR"> <title> Insert title here</title > </head> <body> <% TwitterClient3 tw = new TwitterClient3(); RequestToken requestToken = tw.getRequestToken(); request.getSession().setAttribute("requestToken", requestToken); //request.getSession().setAttribute("tw", tw); String authUrl = requestToken.getAuthorizationURL(); %> <script> location.href = "<%=authUrl %>"; </script> </body> </html> |
3.twitterRedirect.jsp
<%@page import="twitter4j.User" %> <%@page import="com.test.java.social.twitter.TwitterClient3" %> <%@page import="twitter4j.auth.AccessToken" %> <%@page import="twitter4j.auth.RequestToken" %> <%@ page language= "java" contentType ="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <%@ include file="/WEB-INF/views/jsp/include/commonTags.jsp"%> <%@page import="twitter4j.TwitterException" %><%@page import="twitter4j.auth.AccessToken" %><%@page import="twitter4j.Twitter" %><%@page import="twitter4j.TwitterFactory" %><%@page import="twitter4j.auth.RequestToken" %> <!DOCTYPE html "> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang= "ko" lang ="ko"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></ title> </head> <body> <% // twitter에서 넘겨줌 String oauth_token = request.getParameter( "oauth_token"); String oauth_verifier= request.getParameter( "oauth_verifier"); request.getSession().setAttribute("oauth_token", oauth_token); request.getSession().setAttribute("oauth_verifier", oauth_verifier); System.out.println("oauth_token ::" + oauth_token); // signin.jsp에서 저장한 것들 RequestToken token = (RequestToken)request.getSession().getAttribute("requestToken" ); TwitterClient3 tw = new TwitterClient3(); // System.out.print(tw); System.out.println("Session getToken : " + token.getToken()); System.out.println("Session oauthToken : " + oauth_token); tw.getAccessToken(oauth_token, oauth_verifier, token, request); tw.printStatuses(); tw.update(" 죄송합니다. 이 글은 아직 한국어로 지원되지 않습니다." ); tw.friendsIds(); /* //On Twitter twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer("rL2mCgow320zUoSpZz9AEQ", "Q2iYvNaPxgm4y6fqYi1JbHdUKKqohjeKos9wASNRotk"); AccessToken accessToken = null; RequestToken requestToken = (RequestToken )request.getSession().getAttribute("requestToken"); String oauth_verifier= request.getParameter("oauth_verifier"); accessToken = twitter.getOAuthAccessToken(requestToken, oauth_verifier); twitter.setOAuthAccessToken(accessToken); User statuses = twitter.getUserTimeline().get(0).getUser(); System.out.println(statuses); */ %> </body> </html> |
4. twitterUpdate.jsp
<%@page import="twitter4j.auth.AccessToken" %> <%@ page session="true" language="java" contentType= "text/html; charset=EUC-KR" pageEncoding="EUC-KR" %> <%@page import="com.test.java.social.twitter.TwitterClient3" %> <%@page import="twitter4j.auth.RequestToken" %> <!DOCTYPE html "> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=EUC-KR"> <title> Insert title here</title > </head> <body> <% TwitterClient3 tw = new TwitterClient3(); AccessToken accessToken = (AccessToken)request.getSession().getAttribute("SESSION_ACCESS_TOKEN" ); System.out.println("Session Access token : " + accessToken.getToken()); System.out.println("Session Access secret Token : " + accessToken.getTokenSecret()); tw.getAccessToken(accessToken.getToken(), accessToken.getTokenSecret()); tw.update("Access Token 취득후 유지중 입니다. 3" + accessToken.getToken()); %> </body> </html> |
반응형
'Spring' 카테고리의 다른 글
대용량 페이징 기법 (0) | 2014.08.07 |
---|---|
Spring initBinder - @vaild / JSR 303 (0) | 2014.04.07 |
spring 3.2 / tiles3 (2) | 2013.12.18 |
facebook platform login/ 정보 연동 (java/jsp) (0) | 2013.12.10 |
Spring Transaction rollback @Annotation 처리 (선언적 트랜잭션 처리) - 작성중.. (0) | 2012.01.17 |