Explain Codes LogoExplain Codes Logo

How to send HTTP request in Java?

java
http-client
http-request
http-response
Anton ShumikhinbyAnton Shumikhin·Sep 15, 2024
TLDR

Make a speed-run HTTP GET request with HttpClient:

var client = HttpClient.newHttpClient(); var request = HttpRequest.newBuilder(URI.create("http://example.com")).GET().build(); var response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.body()); // Ta-da! That was fast!

Fetching content from http://example.com made easy! Fancy POST? Replace .GET() with .POST(HttpRequest.BodyPublishers.ofString("your-data")).

Mastering the request details

Picture a request as a puzzle with several pieces:

  1. Kick-off using HttpClient.
  2. Piece together the HttpRequest jigsaw - URL, HTTP method, headers, and body.
  3. Send the masterpiece and await a HttpResponse award!
  4. Unwrap the server response gift; savor the status codes and response data goodies.

Even the notorious try-with-resources can't resist this charm:

HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("http://example.com")) .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString("{\"example\":\"data\"}")) .build(); try { HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); // Engage response handling gears } catch (IOException | InterruptedException e) { // These exceptions can't stop us! e.printStackTrace(); }

Tackling complexity

Like peeling an onion! External libraries, such as Apache HttpClient, peel off HTTP request complexity, leaving a fresh request ready for authentication, cookie handling, and more:

CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("http://example.com"); httpPost.setEntity(new StringEntity("Post data")); CloseableHttpResponse response = httpClient.execute(httpPost); try { System.out.println(EntityUtils.toString(response.getEntity())); // Enjoy the clear aroma! } finally { response.close(); // Bye-bye, response! You've served well. }

Overcoming stumbling blocks

Timeouts, redirects, JSON data, stream management - solved with a dash of code flavor!

How to escape a hanging connection

Set timeout values to shoot those lagging connections:

con.setConnectTimeout(5000); con.setReadTimeout(5000); // No time for dilly-dallying!

Chasing redirects

Redirects can't outrun setInstanceFollowRedirects():

con.setInstanceFollowRedirects(true); // Redirects, we've got your number!

Sending JSON data that's pure gold

Set Content-Type and employ OutputStream for fun JSON sending:

con.setRequestProperty("Content-Type", "application/json; utf-8"); try (OutputStream os = con.getOutputStream()) { byte[] input = "{\"name\":\"mkyong\"}".getBytes(StandardCharsets.UTF_8); os.write(input, 0, input.length); }

Stream affairs handled with elegance

Guarantee streams are closed to avoid memory leaks:

try(BufferedReader br = new BufferedReader( new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8))) { // Read response like an old-timey letter }