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?
As mentioned previously, we have to use “Authorization” as our header and “Basic ” + encoded credentials as our value: connection. setRequestProperty("Authorization", authHeaderValue); Finally, we need to actually send the HTTP request, like for example by calling getResponseCode().
Preemptive basic authentication is the practice of sending http basic authentication credentials (username and password) before a server replies with a 401 response asking for them. This can save a request round trip when consuming REST apis which are known to require basic authentication.
URL url = new URL(urlToConnect); HttpURLConnection httpUrlConnection = (HttpURLConnection) url. openConnection(); Step 2: Add headers to the HttpURLConnection using setRequestProperty method.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With