Explain Codes LogoExplain Codes Logo

Http Basic Authentication in Java using HttpClient

java
http-client
http-requests
basic-authentication
Anton ShumikhinbyAnton Shumikhin·Aug 31, 2024
TLDR

Here's your quick solution for HTTP Basic Authentication using Java:

String username = "user"; String password = "pass"; // Magic? No, it's just Base64. String encodedCredentials = Base64.getEncoder().encodeToString((username + ":" + password).getBytes()); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.example.com")) .header("Authorization", "Basic " + encodedCredentials) // Here's your key! .build(); // Handing request over to the postman - HttpClient HttpResponse<String> response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());

Key points:

  • Your username and password take a quick trip through Base64 encoder.
  • They land in the comfy nest of the Authorization header.
  • The entire package gets delivered by HttpClient, hoping for a friendly response.

The Encyclopedia of HTTP basic authentication

We've seen the high-speed, roll'em in, roll'em out version. Now, for those starving for knowledge, let's dig more in-depth.

Once upon a time, HttpURLConnection was king

Before we got the shiny HttpClient, HttpURLConnection was what we used:

URL url = new URL("https://api.example.com"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); // Knock Knock. Who’s there? Post. Post who? Postman without a letter! connection.setDoOutput(true); String auth = "Basic " + new String(Base64.getEncoder().encode((username + ":" + password).getBytes())); connection.setRequestProperty("Authorization", auth); try (OutputStream os = connection.getOutputStream()) { os.write(body.getBytes()); }

Check if your Content-Type header has the right clothing on. Ensure InputStream and OutputStream are used responsibly.

Dodging Exceptions and Troubleshooting Server Errors

Just as life, exceptions are inevitable. Shield your requests with try-catch:

try { // Execute request } catch (IOException | InterruptedException e) { // crying in IOException... e.printStackTrace(); }

Getting a "500 Internal Server Error" is like being told "it's not you, it's me." Probe the request and server logs to find out what's going wrong.

The aristocracy of Apache HttpClient 4

Apache HttpClient has a top hat and a sparkly wand over Java's native HttpURLConnection:

CloseableHttpClient client = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("https://api.example.com"); String encoding = Base64.getEncoder().encodeToString((username + ":" + password).getBytes(StandardCharsets.UTF_8)); // Shhhh... it's a secret! httpPost.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + encoding); // Execute and say goodbye. Closing time! CloseableHttpResponse response = client.execute(httpPost); client.close();

Treat CloseableHttpClient and CloseableHttpResponse like guests. Ensure they feel happy and leave when they should.

Saving HTTP Responses for Memories

Sometimes you want to keep the response forever. Make sure you give it a cozy home:

Files.write(Paths.get("response.txt"), response.body().getBytes());

Debugging, the Sherlock Holmes way

For debugging, you need to be Sherlock at times. Here's how you log your requests and responses:

System.out.println("Request Line: " + request.uri()); System.out.println("Response: " + response.body());

For debug output as controlled as a symphony, consider Log4j or SLF4J.