티스토리 뷰

package json;

import net.sf.json.*;
import java.io.*;
import java.net.*;

public class json_test {

    /**
     * @param args
     */
    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        String getS = getRequest();
        JSONArray json = JSONArray.fromObject(getS);
        
        for( int i=0; i<json.size(); i++ ) {
            JSONObject timeline = (JSONObject)json.get(i);
            //JSONArray
            JSONObject user = timeline.getJSONObject("user");
            
            System.out.println("No : " + (i+1) +
                                ", Source : " +
                                timeline.get("source") +
                                ", Retweeted : " +
                                timeline.get("retweeted") +
                                ", Time_zone : " +
                                user.get("time_zone") +
                                ", Retweet Count : " +
                                timeline.get("retweet_count"));
        }
    }
    
    public static String getRequest() throws IOException {
        String result = "";
        String getRequest = "GET /1/statuses/public_timeline.json HTTP/1.1\r\n" +
                            "Host: api.twitter.com\r\n" +
                            "Connection: close\r\n" +
                            "\r\n";
        
        InetAddress inetAddress = InetAddress.getByName("api.twitter.com");
        Socket tcpSocket = new Socket(inetAddress.getHostAddress(), 80);
        
        OutputStream os_socket = tcpSocket.getOutputStream();
        InputStream is_socket = tcpSocket.getInputStream();
        
        BufferedWriter bufferW = new BufferedWriter(new OutputStreamWriter(os_socket));
        BufferedReader bufferR = new BufferedReader(new InputStreamReader(is_socket));
        
        bufferW.write(getRequest);
        bufferW.flush();
        
        String str = null;
        while( (str=bufferR.readLine()) != null ){
            if( str.startsWith("[") ) result += str;
        }
        
        bufferW.close();
        bufferR.close();
        tcpSocket.close();
        
        return result;
    }

}

'노트 > 소스 코드' 카테고리의 다른 글

[R] Co-occurrence Matrix  (0) 2016.02.09
[Java] Polynomials with integer coefficients  (0) 2016.01.18
[C] Multi Thread Server Example  (0) 2011.12.28
[C++] Dijkstra Algorithm (NOT BRUSH)  (0) 2011.12.28
[C] English Morpheme Analyzer (With Lex)  (0) 2011.12.28
[Java] Simple Thread Example - Horse Race  (0) 2011.12.28
[C] Char, Word, Line Count (With Lex)  (0) 2011.12.28
[JavaScript] Layer Popup Example  (0) 2011.12.28
[Java] Notepad  (0) 2011.12.28
[Java] RSS Reader  (0) 2011.12.28