How do I do a HTTP GET in Java?

David picture David · Sep 28, 2009 · Viewed 379.6k times · Source

How do I do a HTTP GET in Java?

Answer

Kalpak picture Kalpak · Sep 28, 2009

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

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

public class c {

   public static String getHTML(String urlToRead) throws Exception {
      StringBuilder result = new StringBuilder();
      URL url = new URL(urlToRead);
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setRequestMethod("GET");
      BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      String line;
      while ((line = rd.readLine()) != null) {
         result.append(line);
      }
      rd.close();
      return result.toString();
   }

   public static void main(String[] args) throws Exception
   {
     System.out.println(getHTML(args[0]));
   }
}