我正在尝试从需要完全身份验证的 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/