Java: recuperare URL con l'autenticazione HTTPBasic
-
20-09-2019 - |
Domanda
che sto facendo qualche semplice autenticazione HTTP e sto ottenendo un
java.lang.IllegalArgumentException: Illegal character(s) in message header value: Basic OGU0ZTc5ODBk(...trimmed from 76 chars...)
(...more password data...)
che credo sia dovuto a me avere un tempo molto lungo username e password e l'encoder avvolge con un \n
a 76 caratteri. C'è un modo per aggirare il problema? L'URL supporta solo HTTP Auth di base.
Qui è il mio codice:
private class UserPassAuthenticator extends Authenticator {
String user;
String pass;
public UserPassAuthenticator(String user, String pass) {
this.user = user;
this.pass = pass;
}
// This method is called when a password-protected URL is accessed
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, pass.toCharArray());
}
}
private String fetch(StoreAccount account, String path) throws IOException {
Authenticator.setDefault(new UserPassAuthenticator(account.getCredentials().getLogin(), account.getCredentials().getPassword()));
URL url = new URL("https", account.getStoreUrl().replace("http://", ""), path);
System.out.println(url);
URLConnection urlConn = url.openConnection();
Object o = urlConn.getContent();
if (!(o instanceof String))
throw new IOException("Wrong Content-Type on " + url.toString());
// Remove the authenticator back to the default
Authenticator.setDefault(null);
return (String) o;
}
Soluzione
Questo sembra essere un bug in Java .
Hai provato a usare i client HTTP alternativi, come la biblioteca da Apache?
O invece di utilizzare l'Authenticator, impostare manualmente l'intestazione?
URL url = new URL("http://www.example.com/");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Authorization", "Basic OGU0ZTc5ODBkABcde....");
Il valore token è encodeBase64. ( "Username: password")
Altri suggerimenti
Questo funziona per me.
HttpsURLConnection con = null; con = (HttpsURLConnection) obj.openConnection (); . Codifica String = Base64.getEncoder () encodeToString (: .getBytes "Username Password" (StandardCharsets.UTF_8)); con.setRequestProperty ( "Autorizzazione", "Basic "+ encoding.replaceAll (" \ n", ""));
ho scoperto che il carattere illegale è stato causato da "Autorizzazione: Basic", codificato che dovrebbe essere "Autorizzazione", "Basic" + codificato