Home >Java >javaTutorial >How to Authenticate Remote URL Connections in Java and Handle 401 Errors?
When connecting to remote URLs protected by authentication, you may encounter a 401 error. Here's how you can handle authentication programatically using Java.
Original Code:
URL url = new URL(String.format("http://%s/manager/list", _host + ":8080")); HttpURLConnection connection = (HttpURLConnection)url.openConnection();
Solution:
Instead of the provided code, you can use the following approach:
URL url = new URL("location address"); URLConnection uc = url.openConnection(); String userpass = username + ":" + password; String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes())); uc.setRequestProperty ("Authorization", basicAuth); InputStream in = uc.getInputStream();
This native alternative allows you to specify the username and password directly through the setRequestProperty method. The Authorization header is set using a Basic authentication scheme, and the user credentials are encoded using Base64.
The above is the detailed content of How to Authenticate Remote URL Connections in Java and Handle 401 Errors?. For more information, please follow other related articles on the PHP Chinese website!