如何在android中进行HTTP身份验证?

Boh*_*ian 72 android http-authentication

我正在检查类org.apache.http.auth.如果有人有更多的参考或例子?

ces*_*rds 116

对我来说,它有效,

final String basicAuth = "Basic " + Base64.encodeToString("user:password".getBytes(), Base64.NO_WRAP);
Run Code Online (Sandbox Code Playgroud)

Apache HttpCLient:

request.setHeader("Authorization", basicAuth);
Run Code Online (Sandbox Code Playgroud)

HttpURLConnection类:

connection.setRequestProperty ("Authorization", basicAuth);
Run Code Online (Sandbox Code Playgroud)

  • NO_WRAP标志!这很关键.我只是使用默认值,并想知道为什么我一直得到400. (23认同)
  • 你的回答为我节省了很多时间.感谢名单!我的问题确实在错误的标志(DEFAULT). (5认同)
  • 终于,经过很长一段时间...... no_wrap FTW! (5认同)

Chr*_*yle 78

我之前没有遇到过那个特定的软件包,但是它说它是用于客户端的HTTP身份验证,我已经能够在Android上使用java.netAPI 来做,如下所示:

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();
Run Code Online (Sandbox Code Playgroud)

显然你的getPasswordAuthentication()应该做一些比返回常量更聪明的事情.

如果您尝试POST使用身份(例如)进行身份验证,请注意Android问题4326.我已将建议的修复程序链接到该平台,但如果您只想要Basic身份验证,则有一个简单的解决方法:不要使用Authenticator,而是执行此操作:

c.setRequestProperty("Authorization", "basic " +
        Base64.encode("myuser:mypass".getBytes(), Base64.NO_WRAP));
Run Code Online (Sandbox Code Playgroud)

  • 如何处理身份验证失败的事件,比如因为提供的凭据不好? (3认同)

Dmi*_*kov 14

您可以手动插入http标头以请求:

HttpGet request = new HttpGet(...);
request.setHeader("Authorization", "Basic "+Base64.encodeBytes("login:password".getBytes()));
Run Code Online (Sandbox Code Playgroud)


GWu*_*GWu 13

手动方法适用于导入android.util.Base64,但一定要在调用encode时设置Base64.NO_WRAP:

String basicAuth = "Basic " + new String(Base64.encode("user:pass".getBytes(),Base64.NO_WRAP ));
connection.setRequestProperty ("Authorization", basicAuth);
Run Code Online (Sandbox Code Playgroud)