如何在Android中进行HTTP身份validation?
我正在检查出类org.apache.http.auth。 任何更多的参考或例子,如果有人?
我以前没有遇到过这个特定的包,但是它说这是用于客户端的HTTPvalidation,我已经可以在Android上使用java.net
API进行validation了,如下所示:
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()应该可以做一些比返回常量更智能的东西。
如果您正尝试使用身份validation(例如POST
)发出请求,请注意Android问题4326 。 我已经把一个build议的修复链接到了那里的平台上,但是如果你只需要基本的authentication就有一个简单的解决方法:不要打扰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()));
手动方法适用于导入android.util.Base64,但一定要设置Base64.NO_WRAP调用编码:
String basicAuth = "Basic " + new String(Base64.encode("user:pass".getBytes(),Base64.NO_WRAP )); connection.setRequestProperty ("Authorization", basicAuth);
这对我有用
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();