我正在使用 Apache HttpComponents 库连接到我的 AppEngine 应用程序。为了对我的用户进行身份验证,我需要将身份验证令牌传递到应用程序的登录地址(http://myapp.appspot.com/_ah/login?auth=.. 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
}
}
}
我如何阻止客户端遵循重定向?
Thanks.
Update:
根据下面的解决方案,我在创建一个后执行了以下操作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;
}
});
}
比看起来需要的更冗长,但并不像我想象的那么困难。
您可以使用 http 参数来做到这一点:
final HttpParams params = new BasicHttpParams();
HttpClientParams.setRedirecting(params, false);
该方法没有 javadoc,但如果您查看源代码,您可以看到它设置:
句柄重定向 http://hc.apache.org/httpcomponents-client/httpclient/apidocs/org/apache/http/client/params/ClientPNames.html#HANDLE_REDIRECTS
它控制:
定义是否应自动处理重定向
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)