개발
트위터 api를 이용하여 트윗목록 확인하기
에드몽단테스
2011. 5. 16. 17:16
갑작스레 트위터의 글을 홈페이지에 붙이는 작업이 생겼다.
그래서 부랴부랴 api를 찾아보는데 언어에서 막히고 사용방법에서 막히고 어디가 어떤건지도 모르겠고...
한참을 고생하다 겨우 필요한 api를 찾을 수 있었다.
다행이도 인증을 거치지 않고 아이디만 입력하면 작성한 글 및 멘션까지도 보여준다.
접근성을 고려하여 스크립트로 하지 않고 jsp로 직접 작성하였다. 작업할 서버의 상태를 모르기 때문에 라이브러리는 사용하지 않도록 하였다. 순수 jsp 코드다.
트윗내용에 링크가 있는 경우에는 그냥 표시하기에는 밋밋해서 하이퍼링크를 걸었다.
또 작성된 시간을 파악하여 현재시간을 기준으로 얼마나 시간이 지났는지도 표시하였다.
그래서 부랴부랴 api를 찾아보는데 언어에서 막히고 사용방법에서 막히고 어디가 어떤건지도 모르겠고...
한참을 고생하다 겨우 필요한 api를 찾을 수 있었다.
다행이도 인증을 거치지 않고 아이디만 입력하면 작성한 글 및 멘션까지도 보여준다.
접근성을 고려하여 스크립트로 하지 않고 jsp로 직접 작성하였다. 작업할 서버의 상태를 모르기 때문에 라이브러리는 사용하지 않도록 하였다. 순수 jsp 코드다.
<%@ page import="java.io.*"%>
<%@ page import="java.net.*"%>
<%@ page import="java.util.*"%>
<%@ page import="java.util.regex.*"%>
<%@ page import="org.w3c.dom.*"%>
<%@ page import="org.xml.sax.InputSource"%>
<%@ page import="javax.xml.parsers.*"%>
<%
final String apiurl = "http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=admongdantes";
final int max_count = 10;
String[][] info = null;
HttpURLConnection conn = null;
int max = 0;
int k = 0;
try{
URL url = new URL(apiurl);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("accept-language","ko");
DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
byte[] bytes = new byte[4096];
InputStream in = conn.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while(true){
int red = in.read(bytes);
if(red < 0)
break;
baos.write(bytes, 0, red);
}
String xmlData = baos.toString("euc-kr");
baos.close();
in.close();
conn.disconnect();
Document doc = docBuilder.parse(new InputSource(new StringReader(xmlData)));
Element el = (Element)doc.getElementsByTagName("statuses").item(0);
max = el.getChildNodes().getLength();
info = new String[max][];
String reg = "(http:\\/\\/\\w+\\.\\w+(\\.\\w+)?(\\.\\w+)?/\\w+)";
for(int i=0; i<max; i++){
Node node = el.getChildNodes().item(i);
if(!node.getNodeName().equals("status")){
continue;
}
if(k >= max_count) break;
Element el2 = (Element)node;
String text = el2.getElementsByTagName("text").item(0).getFirstChild().getNodeValue();
String created_at = el2.getElementsByTagName("created_at").item(0).getFirstChild().getNodeValue();
Element el3 = (Element)(el2.getElementsByTagName("user").item(0));
String name = el3.getElementsByTagName("name").item(0).getFirstChild().getNodeValue();
String screen_name = el3.getElementsByTagName("screen_name").item(0).getFirstChild().getNodeValue();
String profile_image_url = el3.getElementsByTagName("profile_image_url").item(0).getFirstChild().getNodeValue();
Date date = new Date(created_at);
Pattern p = Pattern.compile(reg);
Matcher m = p.matcher(text);
if(m.find()){
text = text.replaceAll(reg, "<a href='"+m.group(1)+"' target='_blank'>"+m.group(1)+"</a>");
}
long cha = (System.currentTimeMillis() - date.getTime())/1000;
String ago = "";
if(cha < 60) {
ago = "1분전";
}
else if(cha < 3600){
ago = (cha / 60)+"분전";
}
else if(cha < 86400){
ago = (cha / 60 / 60)+"시간전";
}
else{
ago = (cha / 60 / 60 / 24)+"일전";
}
info[i] = new String[]{text,name,screen_name,profile_image_url,ago};
k++;
}
}catch(Exception e){
e.printStackTrace();
}finally{
try{if(conn != null) conn.disconnect(); } catch(Exception e){}
}
%>
<%if(k > 0){%>
<table border="1" width="100%">
<%for(int i=0; i<max; i++){
if(info[i] == null) continue;
%>
<tr>
<td><img src="<%=info[i][3]%>" alt="" /></td>
<td><%=info[i][1]%> <%=info[i][2]%><br /><%=info[i][0]%><br /><%=info[i][4]%></td>
</tr>
<%}%>
</table>
<%}else{%>
<p>트래픽 초과로 잠시 데이터를 가져올 수 없습니다.</p>
<%}%>
<%@ page import="java.net.*"%>
<%@ page import="java.util.*"%>
<%@ page import="java.util.regex.*"%>
<%@ page import="org.w3c.dom.*"%>
<%@ page import="org.xml.sax.InputSource"%>
<%@ page import="javax.xml.parsers.*"%>
<%
final String apiurl = "http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=admongdantes";
final int max_count = 10;
String[][] info = null;
HttpURLConnection conn = null;
int max = 0;
int k = 0;
try{
URL url = new URL(apiurl);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("accept-language","ko");
DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
byte[] bytes = new byte[4096];
InputStream in = conn.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while(true){
int red = in.read(bytes);
if(red < 0)
break;
baos.write(bytes, 0, red);
}
String xmlData = baos.toString("euc-kr");
baos.close();
in.close();
conn.disconnect();
Document doc = docBuilder.parse(new InputSource(new StringReader(xmlData)));
Element el = (Element)doc.getElementsByTagName("statuses").item(0);
max = el.getChildNodes().getLength();
info = new String[max][];
String reg = "(http:\\/\\/\\w+\\.\\w+(\\.\\w+)?(\\.\\w+)?/\\w+)";
for(int i=0; i<max; i++){
Node node = el.getChildNodes().item(i);
if(!node.getNodeName().equals("status")){
continue;
}
if(k >= max_count) break;
Element el2 = (Element)node;
String text = el2.getElementsByTagName("text").item(0).getFirstChild().getNodeValue();
String created_at = el2.getElementsByTagName("created_at").item(0).getFirstChild().getNodeValue();
Element el3 = (Element)(el2.getElementsByTagName("user").item(0));
String name = el3.getElementsByTagName("name").item(0).getFirstChild().getNodeValue();
String screen_name = el3.getElementsByTagName("screen_name").item(0).getFirstChild().getNodeValue();
String profile_image_url = el3.getElementsByTagName("profile_image_url").item(0).getFirstChild().getNodeValue();
Date date = new Date(created_at);
Pattern p = Pattern.compile(reg);
Matcher m = p.matcher(text);
if(m.find()){
text = text.replaceAll(reg, "<a href='"+m.group(1)+"' target='_blank'>"+m.group(1)+"</a>");
}
long cha = (System.currentTimeMillis() - date.getTime())/1000;
String ago = "";
if(cha < 60) {
ago = "1분전";
}
else if(cha < 3600){
ago = (cha / 60)+"분전";
}
else if(cha < 86400){
ago = (cha / 60 / 60)+"시간전";
}
else{
ago = (cha / 60 / 60 / 24)+"일전";
}
info[i] = new String[]{text,name,screen_name,profile_image_url,ago};
k++;
}
}catch(Exception e){
e.printStackTrace();
}finally{
try{if(conn != null) conn.disconnect(); } catch(Exception e){}
}
%>
<%if(k > 0){%>
<table border="1" width="100%">
<%for(int i=0; i<max; i++){
if(info[i] == null) continue;
%>
<tr>
<td><img src="<%=info[i][3]%>" alt="" /></td>
<td><%=info[i][1]%> <%=info[i][2]%><br /><%=info[i][0]%><br /><%=info[i][4]%></td>
</tr>
<%}%>
</table>
<%}else{%>
<p>트래픽 초과로 잠시 데이터를 가져올 수 없습니다.</p>
<%}%>
트윗내용에 링크가 있는 경우에는 그냥 표시하기에는 밋밋해서 하이퍼링크를 걸었다.
또 작성된 시간을 파악하여 현재시간을 기준으로 얼마나 시간이 지났는지도 표시하였다.
반응형