How to send an HTTP request to a HTTP Basic Authentication endpoint in Java without using any external libraries
One common task for Java developers is to write codes that communicate with API endpoints. Chances are these endpoints could use HTTP Basic Authentication for authenticating the HTTP request sender.
Although there are good libraries to help us craft and send HTTP requests to a web server in Java, I prefer to use the Java core library so as to keep my Java program lightweight.
Referencing my earlier post on how to construct a HTTP request to an endpoint with HTTP basic authentication, this post documents how to send an HTTP request to a HTTP Basic Authentication endpoint in Java without using any external libraries.
Using httpbin.org to test our HTTP request with HTTP Basic Authentication
For the sake of brevity, we will use an endpoint from httpbin.org to test out the Java codes that we are going to write.
This endpoint is available at http://httpbin.org/basic-auth/user/passwd. It expects a HTTP Basic Authentication request with:
- HTTP GET as the HTTP method,
- user as the username
- and passwd as the password
Java codes for generating a Base64 encoded String payload from a username and password pair
The first step in crafting a HTTP request for a HTTP Basic Authentication endpoint is to generate a Base64 encoded String payload from the username and password. Lucky for us, Java 8 provided java.util.Base64
to help us with Base64 encoding.
The following Java 8 codes generate a Base64 encoded String payload with user as the username and passwd as the password:
String usernameColonPassword = "user:passwd"; String basicAuthPayload = "Basic " + Base64.getEncoder().encodeToString(usernameColonPassword.getBytes());
To generate the HTTP Basic Authentication payload, we simply:
- concatenate the username, a colon and the password,
- pass the concatenated String as bytes to
Base64.getEncoder().encodeToString
to get a Base64 encoded String, - and prepend the Base64 encode String with the String "Basic ".
Java codes for sending HTTP request to the HTTP Basic Authentication endpoint
With the basicAuthPayload
, we can then proceed with crafting and sending the HTTP request to the HTTP Basic Authentication endpoint.
To avoid external libraries, we can use the following classes that are provided by the Java code library for sending the HTTP request:
- java.io.BufferedReader
- java.io.BufferedWriter
- java.io.File
- java.io.FileInputStream
- java.io.InputStreamReader
- java.io.OutputStream
- java.io.OutputStreamWriter
- java.net.HttpURLConnection
- java.net.URL
And write the following codes to send a HTTP GET request to a HTTP Basic Authentication endpoint:
BufferedReader httpResponseReader = null; try { // Connect to the web server endpoint URL serverUrl = new URL("http://httpbin.org/basic-auth/user/passwd"); HttpURLConnection urlConnection = (HttpURLConnection) serverUrl.openConnection(); // Set HTTP method as GET urlConnection.setRequestMethod("GET"); // Include the HTTP Basic Authentication payload urlConnection.addRequestProperty("Authorization", basicAuthPayload); // Read response from web server, which will trigger HTTP Basic Authentication request to be sent. httpResponseReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); String lineRead; while((lineRead = httpResponseReader.readLine()) != null) { System.out.println(lineRead); } } catch (IOException ioe) { ioe.printStackTrace(); } finally { if (httpResponseReader != null) { try { httpResponseReader.close(); } catch (IOException ioe) { // Close quietly } } }
Putting it together
The following is a Java main class that contains all the codes that we had discussed:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.Base64; public class HttpBasicAuthenticationExample { public static void main(String[] args) { String usernameColonPassword = "user:passwd"; String basicAuthPayload = "Basic " + Base64.getEncoder().encodeToString(usernameColonPassword.getBytes()); BufferedReader httpResponseReader = null; try { // Connect to the web server endpoint URL serverUrl = new URL("http://httpbin.org/basic-auth/user/passwd"); HttpURLConnection urlConnection = (HttpURLConnection) serverUrl.openConnection(); // Set HTTP method as GET urlConnection.setRequestMethod("GET"); // Include the HTTP Basic Authentication payload urlConnection.addRequestProperty("Authorization", basicAuthPayload); // Read response from web server, which will trigger HTTP Basic Authentication request to be sent. httpResponseReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); String lineRead; while((lineRead = httpResponseReader.readLine()) != null) { System.out.println(lineRead); } } catch (IOException ioe) { ioe.printStackTrace(); } finally { if (httpResponseReader != null) { try { httpResponseReader.close(); } catch (IOException ioe) { // Close quietly } } } } }
Running the above code will produce the following output:
{ "authenticated": true, "user": "user" }
You may wish to change the String literal that is assigned to the usernameColonPassword
variable and observe what happens.