3

我正在尝试从需要完全身份验证的 android 访问 web 服务。为此,我正在使用基本 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>

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

提前致谢。

4

1 回答 1

3

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

requestLogin.addHeader("Authorization", "Basic " +
    Base64.encodeToString((username+":"+password).getBytes(), Base64.DEFAULT));
于 2013-05-26T13:15:06.987 回答