tags:

views:

243

answers:

4

Hello,

How do I do a HTTP GET in Java?

Thanks.

David

+10  A: 

Technically you could do it with a straight TCP socket. I wouldn't recommend it however. I would highly recommend you use Apache HttpClient instead. In it's simplest form:

GetMethod get = new GetMethod("http://httpcomponents.apache.org");
// execute method and handle any error responses.
...
InputStream in = get.getResponseBodyAsStream();
// Process the data from the input stream.
get.releaseConnection();

and here is a more complete example.

cletus
+3  A: 

If you want to stream any webpage, you can use the method below.

import java.io.*;
import java.net.*;

public class c {

   public String getHTML(String urlToRead) {
      URL url;
      HttpURLConnection conn;
      BufferedReader rd;
      String line;
      String result = "";
      try {
         url = new URL(urlToRead);
         conn = (HttpURLConnection) url.openConnection();
         conn.setRequestMethod("GET");
         rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
         while ((line = rd.readLine()) != null) {
            result += line;
         }
         rd.close();
      } catch (Exception e) {
         e.printStackTrace();
      }
      return result;
   }

   public static void main(String args[])
   {
     c c = new c();
     System.out.println(c.getHTML(args[0]));
   }
}

Kalpak
One of the advantages of cletus's answer (using Apache HttpClient) is that HttpClient can automatically handle redirects and proxy authentication for you. The standard Java API classes that you use here don't do that for you. On the other hand, using the standard API classes has the advantage that you don't need to include a third-party library in your project.
Jesper
+3  A: 

The simplest way that doesn't require third party libraries it to create a URL object and then call either openConnection or openStream on it. Note that this is a pretty basic API, so you won't have a lot of control over the headers.

Laurence Gonsalves
A: 

If you dont want to use external libraries, you can use URL and URLConnection classes from standard Java API.

An example looks like this:

urlString = "http://wherever.com/someAction?param1=value1&param2=value2....";
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream() 
// Do what you want with that stream
HyLian
@HyLian: given the apparent level of the OP's question, your code fragment should include a try { } finally { } to tidy up.
Stephen C
@Stephen C: For sure, that was only a code fragment to show what classes are in the game and how to use them. If you put that in a real program you should play the exception rules :)
HyLian