Preemptive Basic Auth with HttpUrlConnection?

If you are using Java 8 or later, java.util.Base64 is usable:

HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
String encoded = Base64.getEncoder().encodeToString((username+":"+password).getBytes(StandardCharsets.UTF_8));  //Java 8
connection.setRequestProperty("Authorization", "Basic "+encoded);

Then use the connection as normal.

If you’re using Java 7 or lower, you’ll need a method to encode a String to Base64, such as:

byte[] message = (username+":"+password).getBytes("UTF-8");
String encoded = javax.xml.bind.DatatypeConverter.printBase64Binary(message);

Yes, that’s all you have to do in order to use Basic Auth. The code above to set the Request Property should be done immediately after opening the connection and before getting the Input or Output streams.

Leave a Comment