Grab Twitter Search JSON using simple JAVA bufferStream


Open JSON files from twitter search using JAVA is easy. We can use simple buffer stream reader. Here is the example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import java.io.BufferedReader;  // 1
import java.io.InputStreamReader;
import java.net.URL;

public class OpenWebsite {
    public static void main (String[] args) throws Exception { // 2
    URL twitter = new URL("http://search.twitter.com/search.json?q=" +
                  "blue%20angels&rpp=5&include_entities=true" +
                  "&result_type=mixed"); // 3
    BufferedReader in = new BufferedReader(
        new InputStreamReader(twitter.openStream())); // 4
   
    String output;  // 5
    while((output = in.readLine()) != null) {
        System.out.println(output);  // 6
    }
    }
}


Code Explanation:
1. Start with import three packages BufferedReader and InputStreamReader from java.io and URL from java.net.
2. Create main() with throws Exception to handle error when opening URL.
3. Define target url and wrap it inside URL objects.
4. With BufferedReader, we try to read InputStreamReader from openStream() in twitter variable.
5. Define new String to receive information from input readline
6. Read the results

Instead of directly read from URL objects, we can read it from URLConnection objects. Which, URL objects will start doing remote connection after execute connect() method in URLConnection objects.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
 * Example of Opening URL from URLConnection objects
 */

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class ReadFromURLConnection {
    public static void main(String[] args) throws Exception {
    URL google = new URL("http://google.com");
    URLConnection myRemote = google.openConnection();
    BufferedReader in = new BufferedReader(
            new InputStreamReader(myRemote.getInputStream()));
   
    String inputLine;
    while((inputLine = in.readLine()) != null)
        System.out.println(inputLine);
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.