How do I do a HTTP GET in Java?

JavaHttpGetHttpurlconnection

Java Problem Overview


How do I do a HTTP GET in Java?

Java Solutions


Solution 1 - Java

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");
      try (BufferedReader reader = new BufferedReader(
                  new InputStreamReader(conn.getInputStream()))) {
          for (String line; (line = reader.readLine()) != null; ) {
              result.append(line);
          }
      }
      return result.toString();
   }

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

Solution 2 - Java

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 its 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.

Solution 3 - Java

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

An example looks like this:

String 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

Solution 4 - Java

The simplest way that doesn't require third party libraries it to create a URL object and then call either http://java.sun.com/javase/6/docs/api/java/net/URL.html#openConnection()">openConnection</a> or http://java.sun.com/javase/6/docs/api/java/net/URL.html#openStream()">openStream</a> on it. Note that this is a pretty basic API, so you won't have a lot of control over the headers.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDavidView Question on Stackoverflow
Solution 1 - JavaKalpakView Answer on Stackoverflow
Solution 2 - JavacletusView Answer on Stackoverflow
Solution 3 - JavaHyLianView Answer on Stackoverflow
Solution 4 - JavaLaurence GonsalvesView Answer on Stackoverflow