【问题标题】:HttpClient Authentication in AndroidAndroid中的HttpClient身份验证
【发布时间】:2013-05-26 12:00:32
【问题描述】:

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

我已尝试设置 UserNamePasswordCredentials 以及在 HttpGet 请求中设置标头,但一切都在脉络中。请告诉我我做错了什么。

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

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>

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

提前致谢。

【问题讨论】:

    标签: android authentication httpclient


    【解决方案1】:

    我刚刚尝试了手动 http 标头变体,它应该与 Base64.Default 标志一起使用:

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

    【讨论】:

    • 我试过了,但它返回“您的浏览器发送了一个此服务器无法理解的请求”
    • 尝试使用 Firefox 和打开的 Web 控制台登录 Web 服务。然后单击请求并查看授权标头。它真的从Basic开始吗?将以下 base64 字符串与您的代码生成的字符串进行比较。
    • 谢谢@Torben。我以前的代码对我有用。问题是由于我的用户名中的“\”字符造成的。在您的帮助下对其进行解码。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-29
    • 2019-04-15
    • 1970-01-01
    • 2018-08-12
    相关资源
    最近更新 更多