我正在检查org.apache.http.auth类。还有其他参考或示例吗?
Answers:
我之前没有见过那个特定的程序包,但是它说它是用于客户端HTTP身份验证的,我已经可以使用java.net
API在Android上完成此操作,如下所示:
Authenticator.setDefault(new Authenticator(){
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("myuser","mypass".toCharArray());
}});
HttpURLConnection c = (HttpURLConnection) new URL(url).openConnection();
c.setUseCaches(false);
c.connect();
显然,您的getPasswordAuthentication()应该比返回常量更智能。
如果您尝试POST
通过身份验证的正文(例如)发出请求,请注意Android问题4326。我已经将建议的修复程序链接到那里的平台,但是如果您只想要基本身份验证,则有一个简单的解决方法:不要打扰Authenticator,而是这样做:
c.setRequestProperty("Authorization", "basic " +
Base64.encode("myuser:mypass".getBytes(), Base64.NO_WRAP));
对我来说,它奏效了
final String basicAuth = "Basic " + Base64.encodeToString("user:password".getBytes(), Base64.NO_WRAP);
Apache HttpCLient:
request.setHeader("Authorization", basicAuth);
HttpUrlConnection:
connection.setRequestProperty ("Authorization", basicAuth);
您可以手动插入http标头以请求:
HttpGet request = new HttpGet(...);
request.setHeader("Authorization", "Basic "+Base64.encodeBytes("login:password".getBytes()));
这对我有用
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) imageUrl
.openConnection();
conn.setRequestProperty("Authorization", "basic " +
Base64.encode("username:password".getBytes()));
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is = conn.getInputStream();