Connecting to remote URL which requires authentication using Java
You can set the default authenticator for http requests like this:
Authenticator.setDefault (new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication ("username", "password".toCharArray()); }});
Also, if you require more flexibility, you can check out the Apache HttpClient, which will give you more authentication options (as well as session support, etc.)
There's a native and less intrusive alternative, which works only for your call.
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();
You can also use the following, which does not require using external packages:
URL url = new URL(“location address”);URLConnection uc = url.openConnection();String userpass = username + ":" + password;String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes());uc.setRequestProperty ("Authorization", basicAuth);InputStream in = uc.getInputStream();