Sunday, 11 October 2015

URLConnection : Reading data from a server

It is a four step process.
1. Construct URL Object
         URL url = new URL(resource);

2. Open connection to URL object
         URLConnection conn = url.openConnection();

3. Get the input stream from URL connection


4. Read data and close the connection
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class Main {

  public static String readData(String resource) {
    try {
      /* Construct URL object */
      URL url = new URL(resource);

      /* Open URLConnection to this URL */
      URLConnection conn = url.openConnection();

      /* Get input Stream for the connection */
      InputStream is = conn.getInputStream();
      BufferedReader br = new BufferedReader(new InputStreamReader(is));

      /* Read data from connection and print */
      String str;
      while ((str = br.readLine()) != null) {
        System.out.println(str);
      }
      
      br.close();

    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    return null;
  }

  public static void main(String args[]) throws UnsupportedEncodingException {
    String resource = "https://self-learning-java-tutorial.blogspot.com";
    System.out.println(readData(resource));
  }
}

Note
Invoking the close() methods on the InputStream or OutputStream of an URLConnection after a request may free network resources associated with this instance.



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment