我正在使用 Apache HttpComponents 库连接到我的 AppEngine 应用程序。为了对我的用户进行身份验证,我需要将身份验证令牌传递给应用程序的登录地址(http://myapp.appspot.com/_ah/login?auth=.. .)并从标题中获取 cookie回复。但是,登录页面以重定向状态代码响应,我不知道如何阻止 HttpClient 跟随重定向,从而阻止我拦截 cookie。
Fwiw,我用来发送请求的实际方法如下。
private void execute(HttpClient client, HttpRequestBase method) {
// Set up an error handler
BasicHttpResponse errorResponse = new BasicHttpResponse(
new ProtocolVersion("HTTP_ERROR", 1, 1), 500, "ERROR");
try {
// Call HttpClient execute
client.execute(method, this.responseHandler);
} catch (Exception e) {
errorResponse.setReasonPhrase(e.getMessage());
try {
this.responseHandler.handleResponse(errorResponse);
} catch (Exception ex) {
// log and/or handle
}
}
}
我将如何阻止客户端遵循重定向?
谢谢。
更新:
根据下面的解决方案,我在创建 a 之后DefaultHttpClient client
(以及在将其传递给execute
方法之前)执行了以下操作:
if (!this.followRedirect) {
client.setRedirectHandler(new RedirectHandler() {
public URI getLocationURI(HttpResponse response,
HttpContext context) throws ProtocolException {
return null;
}
public boolean isRedirectRequested(HttpResponse response,
HttpContext context) {
return false;
}
});
}
比它看起来需要的更冗长,但没有我想象的那么难。