好吧,我正试图找到一种方法来让http组件跟随重定向,但在google上找不到任何内容,所以我来这里寻求帮助 功能:
public String GetSite(String site, String path) throws Exception {
HttpParams params = new SyncBasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
HttpProtocolParams.setUseExpectContinue(params, true);
HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[]{
// Required protocol interceptors
new RequestContent(),
new RequestTargetHost(),
// Recommended protocol interceptors
new RequestConnControl(),
new RequestUserAgent(),
new RequestExpectContinue()});
HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
HttpContext context = new BasicHttpContext(null);
HttpHost host = new HttpHost(site, 80);
DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();
context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);
try {
String[] targets = {
path};
for (int i = 0; i < targets.length; i++) {
if (!conn.isOpen()) {
Socket socket = new Socket(host.getHostName(), host.getPort());
conn.bind(socket, params);
}
BasicHttpRequest request = new BasicHttpRequest("GET", targets[i]);
request.setParams(params);
httpexecutor.preProcess(request, httpproc, context);
HttpResponse response = httpexecutor.execute(request, conn, context);
response.setParams(params);
httpexecutor.postProcess(response, httpproc, context);
if (!connStrategy.keepAlive(response, context)) {
conn.close();
} else {
}
return (EntityUtils.toString(response.getEntity()));
}
} finally {
conn.close();
}
return null;
}
对此也有任何帮助吗?因为我找不到任何东西......
答案 0 :(得分:2)
我建议您使用支持重定向的基本DefaultHttpClient
,无需任何调整或其他代码。它的行为可以通过section 5.2 HttpClient parameters中描述的4个参数来控制。
如果你真的不想依赖httpcomponents-client
而只依赖httpcomponents-core
,你必须选择implementation from org.apache.http.impl.client.RedirectStrategy
并创建自己的代码来解析响应,确定它是否是一个有效的重定向(仔细阅读HTTP规范,这不是那么简单)并在需要时在循环中触发一个新请求。
我的观点:没有理由再次编写如此复杂的代码,并且有一天需要进行身份验证,您也必须添加该支持。所以,只需依靠HttpClient。