当尝试访问使用基本身份验证保护的服务器时,我的第一个请求总是失败,但第二个请求以相同的凭据成功。
以下是相关方法:
// username and password are entered by the user, the serviceurl is the endpoint on the server
private boolean testHttpLogin(String username, String password, String serviceUrl) {
if (username != null && username.length() > 0 && password != null && password.length() > 0) {
try {
Response<String> serverResponse = null;
serverResponse = Ion.with(getApplicationContext()).load(serviceUrl).noCache()
.basicAuthentication(username, password)
.asString().withResponse().get();
logger.debug("response in testLogin: " + serverResponse.getResult());
int responseCode = serverResponse.getHeaders().code();
if (responseCode != HttpURLConnection.HTTP_UNAUTHORIZED) {
taskUserName = username;
taskPassword = password;
logger.info("Login successful!");
return true;
} else {
logger.info("Login failed!");
BasisUtils.showToast("User not authorized!");
}
}
catch (ExecutionException | InterruptedException e) {
[...] // handle exceptions...
}
return false;
}
}
因此,当用户尝试登录时,第一次它将以'未授权'的形式返回,并且当他第二次尝试(不更改任何输入)时,它可以正常工作。
我已经尝试过的事情:
第一个请求的响应头如下:
Date: Fri, 12 Jun 2015 13:00:00 GMT
Server: Apache
WWW-Authenticate: Basic realm="somerealm"
Content-Length: 381
Keep-Alive: timeout=15, max=100
Connection: Keep-Alive
Content-Type: text/html; charset=iso-8859-1
成功登录的标题如下所示:
date: Fri, 12 Jun 2015 14:28:15
server: Apache
x-powered-by: ASP.NET
x-aspnet-version: 2.0.50727
x-xss-protection: 1; mode=block
x-frame-options: SAMEORIGIN
cache-control: private, must-revalidate, max-age=0
content-type: text/html;charset=utf-8
set-cookie:[the token I need]; Expires=Fri, 12-Jun-2015 14:29:12 GMT; Path=/path/on/server; HttpOnly
vary: Accept-Encoding
content-encoding: gzip
content-length: 1689
keep-alive: timeout=15, max=98
请求标头如下所示:
Host: mobile.myserver.com:4434
User-Agent: Dalvik/1.6.0 (Linux; U; Android 4.1.2; GT-P5100 Build/JZO54K)
Accept-Encoding: gzip, deflate
Connection: keep-alive
Accept: */*
Cache-Control: no-cache
Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ= // exchanged the real credentials against username:password
两个请求都是一样的。
今天查看标题时,我注意到先前连接到服务器的标题中包含了一个cookie(我必须在用户登录之前检查服务器上的身份验证方法)。我现在在发出请求之前删除所有cookie(以防cookie对请求无效):
Ion.getDefault(getApplicationContext()).getCookieMiddleware().getCookieStore().removeAll();
serverResponse = Ion.with(getApplicationContext()).load(serviceUrl).noCache()
.setLogging("ION VERBOSE", Log.VERBOSE).basicAuthentication(username, password)
.asString().withResponse().get();
我只是看得更远,它变得更加混乱。显然,第二个请求甚至不必在同一个“应用程序会话”中(即我可以通过设置强制停止应用程序,重新打开它,请求仍然会成功)。