我正在检查类org.apache.http.auth。 如果有人有更多的参考或例子吗?
答案 0 :(得分:116)
对我来说,它有效,
final String basicAuth = "Basic " + Base64.encodeToString("user:password".getBytes(), Base64.NO_WRAP);
Apache HttpCLient:
request.setHeader("Authorization", basicAuth);
HttpURLConnection类:
connection.setRequestProperty ("Authorization", basicAuth);
答案 1 :(得分:78)
之前我没有遇到过这个特定的软件包,但是它说它是用于客户端的HTTP身份验证,我已经能够在Android上使用java.net
API执行此操作,如下所示:
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 issue 4326。我已将建议的修复程序链接到那里的平台,但如果您只想要Basic身份验证,则有一个简单的解决方法:不要使用Authenticator,而是执行此操作:
c.setRequestProperty("Authorization", "basic " +
Base64.encode("myuser:mypass".getBytes(), Base64.NO_WRAP));
答案 2 :(得分:14)
您可以手动插入http标头以请求:
HttpGet request = new HttpGet(...);
request.setHeader("Authorization", "Basic "+Base64.encodeBytes("login:password".getBytes()));
答案 3 :(得分:12)
手动方法适用于导入android.util.Base64,但一定要在调用encode时设置Base64.NO_WRAP:
String basicAuth = "Basic " + new String(Base64.encode("user:pass".getBytes(),Base64.NO_WRAP ));
connection.setRequestProperty ("Authorization", basicAuth);
答案 4 :(得分:3)
答案 5 :(得分:1)
这对我有用
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();