Explain Codes LogoExplain Codes Logo

How do I do a HTTP GET in Java?

java
http-requests
okhttp
httpurlconnection
Nikita BarsukovbyNikita Barsukov·Feb 12, 2025
TLDR

Here's a barebones example of an HTTP GET request with Java's HttpURLConnection:

import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class SimpleHttpGet { public static void main(String[] args) throws Exception { URL url = new URL("http://example.com"); // Ahoy, internet! HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); // Ready to GET us some data! BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream())); String line; StringBuilder result = new StringBuilder(); while ((line = reader.readLine()) != null) { // slurping the data result.append(line); } reader.close(); // Bye, reader! System.out.println(result); // Data, glorious data! } }

With this code, you create a connection, set the request method to "GET", and read the response with a BufferedReader. This is GETting exciting!

Hang on, there's more. To handle data and parameters in HTTP GET requests, you can:

  • append parameters directly to the URL string.
  • use URL encoding for parameter values to handle special characters.
  • set request headers with conn.setRequestProperty("header-name", "header-value");.
  • remember to clean up your toys; i.e., con.disconnect() when you're done.

Where there's a library, there's a way

HttpURLConnection is good for simple requests, but when things get feisty, libraries like Apache HttpClient or OkHttp can provide:

  • Fluent APIs to build requests without going insane
  • Connection pooling for better performance
  • Automatic retry policies because computers fail
  • Easier response handling with automatic JSON parsing because who has the time?

Here's a code snippet using OkHttp:

OkHttpClient client = new OkHttpClient(); // Call me HttpClient... OkHttpClient Request request = new Request.Builder() .url("http://example.com") // I want my data from here .build(); // All set, Cap'n! Response response = client.newCall(request).execute(); // Executing order 66... ummm... GET request String responseBody = response.body().string(); // What do we have here?

Beyond happy paths – error handling

Every superhero needs a plan B. And so does your program. Here's how you can save the day:

  • Wrap network operations with try-catch blocks to catch IOException.
  • Use specific catch blocks for MalformedURLException or ProtocolException.
  • Check HttpURLConnection.getResponseCode() to handle HTTP status 404... and the other ones.

Attention: Secure your requests

When it's about HTTPS, not Hand-Tossed Pizza Service:

  • Verify the certificate with SSLContext and TrustManager because security first!
  • Ensure that URL starts with "https://". That 'S' matters.
  • When in doubt, consider libraries like Apache HttpClient with built-in HTTPS support.

Tips and tricks from the trenches

Efficiency with streams

Working with streams? Take these tips on board:

  • Use a buffered approach in case of large data attacks.
  • Close streams in a finally block or use try-with-resources to seal the deal.

Handling cHaRaCtEr EnCoDiNg

Don't let special characters ruin your GET party:

  • Use URLEncoder.encode(value, "UTF-8") to be on the safe side.
  • When in Rome, do as the Romans do. Check the server's encoding norms.

Parameters and headers – Do's and Don'ts

  • Keep your parameters tidy with collections like Map<String, String>.
  • Headers, like people, can't function with null values, Check before you set!