Tuesday, April 9, 2013
Today I will tell you how you can send a HTTP request from your simple Java program and then read the data(HTML) sent from the server. This is actually the process which is carried out by browsers when you type the url in its address bar. The browser receives the data and then parses and displays it. Here we will omit the parsing and only print the data received from server on the console. The request to the url here is a HTTP GET request. The following classes are used
java.net.URL : This class represents the Uniform Resource Locator and points to a resource. Here we will use openConnection() method to connect to the url and get a URLConnection reference.
java.ney.URLConnection : The abstract class URLConnection is the superclass of all classes that represent a communications link between the application and a URL. We will call getInputStream() to get a stream to that url which is used for reading data from url or server.
--------------------------------------------------------------------------------------------------------------------------
Java Source Code
--------------------------------------------------------------------------------------------------------------------------
import java.net.URL;
import java.net.URLConnection;
import java.io.*;

public class URLConnectionReader {
  public static void main(String[] args) throws Exception {
    URL url = new URL(args[0]);  //url read from command line
    URLConnection c = url.openConnection();  //connecting to url
    BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream()));  //stream to resource
    String str;
    while ((str = in.readLine()) != null)   //reading data
       System.out.println(str);  //printing data read from url to console
    in.close();  //closing stream
  }
}

2 comments:

  1. is this code run's on android too?

    ReplyDelete
  2. says to me : what can i do?
    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
    at crypto.URLConnectionReader.main(URLConnectionReader.java:18)

    ReplyDelete

Total Pageviews

Followers


Labels

Popular Posts

free counters