جافا: جلب عنوان URL مع مصادقة httpbasic
-
20-09-2019 - |
سؤال
أقوم ببعض مصادقة HTTP البسيطة وأحصل على ملف
java.lang.IllegalArgumentException: Illegal character(s) in message header value: Basic OGU0ZTc5ODBk(...trimmed from 76 chars...)
(...more password data...)
وهو ما أعتقد أنه بسبب وجود اسم مستخدم وكلمة مرور طويلة حقًا ، ويلتفها المشفر مع أ \n
في 76 chars. هل هناك أي طريقة يمكنني الالتفاف على هذا؟ يدعم عنوان URL فقط HTTP Basic Auth.
ها هو رمزتي:
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;
}
المحلول
يبدو أن هذا علة في جافا.
هل حاولت استخدام عملاء HTTP البديل ، مثل المكتبة من Apache؟
أو بدلاً من استخدام المصادقة ، وضع الرأس يدويًا؟
URL url = new URL("http://www.example.com/");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Authorization", "Basic OGU0ZTc5ODBkABcde....");
قيمة الرمز المميز هي Encodebase64 ("اسم المستخدم: كلمة المرور").
نصائح أخرى
هذا يعمل بالنسبة لي.
httpsurlConnection con = null ؛ con = (httpsurlConnection) obj.openconnection () ؛ سلسلة الترميز = base64.getenCoder (). encodetoString ("اسم المستخدم: كلمة المرور" .getBytes (standardcharsets.utf_8)) ؛ consetRequestProperty ("إذن" ، "BASIC"+isoding.replaceall (" n" ، "")) ؛
لقد وجدت أن الشخصية غير القانونية كانت ناتجة عن "إذن: أساسي" ، مشفر الذي يجب أن يكون "إذنًا" ، "أساسي" + مشفر