android - Android 中的 HttpClient 身份验证

标签 android authentication httpclient

我正在尝试从需要完全身份验证的 android 访问网络服务。为此,我正在使用基本的 http 身份验证。

我已经尝试设置 UserNamePasswordCredentials 以及在 HttpGet 请求中设置 header ,但都是在静脉中。请告诉我我做错了什么。

我用于在 HttpGet 请求中设置 header 的代码:

HttpGet requestLogin = new HttpGet(url);               
requestLogin.addHeader("Authorization", "Basic " + Base64.encodeToString((username+":"+password).getBytes(), Base64.NO_WRAP));

我用来设置 UserNamePassword 凭据的代码:

DefaultHttpClient httpClient = new DefaultHttpClient(mgr, tempClient.getParams());
httpClient.getCredentialsProvider().setCredentials(
                   AuthScope.ANY,
                    new UsernamePasswordCredentials(username,password));

这是我在使用这段代码时遇到的异常:

05-26 17:21:22.234: E/res(1651): <html><head><title>Apache Tomcat/6.0.35 - Error report</title><style><!--H1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} B {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} P {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;}A {color : black;}A.name {color : black;}HR {color : #525D76;}--></style> </head><body><h1>HTTP Status 401 - Bad credentials</h1><HR size="1" noshade="noshade"><p><b>type</b> Status report</p><p><b>message</b> <u>Bad credentials</u></p><p><b>description</b> <u>This request requires HTTP authentication (Bad credentials).</u></p><HR size="1" noshade="noshade"><h3>Apache Tomcat/6.0.35</h3></body></html>

当我在浏览器上使用这些相同的凭据时,它起作用了。所以凭据不是不正确的。请让我知道我做错了什么。我完全陷入其中。

提前致谢。

最佳答案

我刚刚尝试了手动 http header 变体,它应该与 Base64 一起使用。默认标志:

requestLogin.addHeader("Authorization", "Basic " +
    Base64.encodeToString((username+":"+password).getBytes(), Base64.DEFAULT));

关于android - Android 中的 HttpClient 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16759024/

相关文章:

java - http调用执行中的资源泄漏

android - 如何在相同的 View 上同时播放 Fade 和 Slide 过渡?

ruby-on-rails - 设计:确认后运行代码

.net - 断开连接时使用 .Net 对 Active Directory 进行身份验证

Java http 客户端 - 从 javascript 刷新后获取页面内容

android - 如何拦截 Intent (用于日历事件创建)

android - 从 RecyclerView 获取缓存项

php - Drupal 8 外部/自定义身份验证提供程序

java - POST 请求在 Java 客户端中不起作用,但在 postman 中起作用

Angular 4 : http client module get request. API key 放置