Java – Preemptive Basic Auth with HttpUrlConnection

androidauthenticationbasic-authenticationhttpjava

What is the best way to use preemptive basic http authentication using HttpUrlConnection. (Assume for now I can't use HttpClient).

EDIT for clarification: I'm setting the un/pw correctly in the request header using Base64 encoding. Are there any additional flags or properties that need to be set, or is the fact that I'm setting the basic auth headers for the request all that is needed for preemptive basic auth?

Best Answer

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.