防止 HttpClient 4 跟随重定向 [英] Preventing HttpClient 4 from following redirect
问题描述
我正在使用 Apache HttpComponents 库连接到我的 AppEngine 应用程序.为了对我的用户进行身份验证,我需要将身份验证令牌传递到应用程序的登录地址 (http://myapp.appspot.com/_ah/login?auth=...) 并从响应的标头中获取 cookie.但是,登录页面响应重定向状态码,我不知道如何阻止HttpClient跟随重定向,从而阻止我拦截cookie.
I'm connecting to my AppEngine application using the Apache HttpComponents library. In order to authenticate my users, I need to pass an authentication token along to the application's login address (http://myapp.appspot.com/_ah/login?auth=...) and grab a cookie from the header of the response. However, the login page responds with a redirect status code, and I don't know how to stop HttpClient from following the redirect, thus thwarting me from intercepting the cookie.
Fwiw,我用来发送请求的实际方法如下.
Fwiw, the actual method I use to send the request is below.
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
}
}
}
如何阻止客户端跟随重定向?
How would I stop the client from following the redirect?
谢谢.
更新:
根据下面的解决方案,我在创建一个 DefaultHttpClient 客户端
之后(并且在将它传递给 execute
方法之前)做了以下操作:
As per the solution below, I did the following after creating a DefaultHttpClient client
(and before passing it to the execute
method):
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;
}
});
}
比看起来更冗长,但没有我想象的那么难.
More verbose than it seems it needs to be, but not as difficult as I thought.
推荐答案
尝试使用 RedirectHandler
.这可能需要扩展 DefaultHttpClient
从 createRedirectHandler()
返回您的自定义实现.
Try using a RedirectHandler
. That may require extending DefaultHttpClient
to return your custom implementation from createRedirectHandler()
.
这篇关于防止 HttpClient 4 跟随重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!