首先,我看不出为什么不能用 Apache HttpClient 来完成。您是否将客户端配置为使用“http.route.default-proxy”参数通过代理执行请求?
无论如何,如果您不介意使用较低的组件,这就是使用 Apache HttpCore(阻塞)可以完成的相同操作
HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
new RequestContent(),
new RequestTargetHost(),
new RequestConnControl(),
new RequestUserAgent()});
HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();
HttpContext context = new BasicHttpContext();
HttpHost target = new HttpHost("www.cached", port);
HttpHost proxy = new HttpHost("squid", 8080);
HttpParams params = new BasicHttpParams();
HttpRequest request = new BasicHttpRequest("PURGE", "www.cached:port/params");
DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
try {
if (!conn.isOpen()) {
Socket socket = new Socket(proxy.getHostName(), proxy.getPort());
conn.bind(socket, params);
}
context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, target);
httpexecutor.preProcess(request, httpproc, context);
HttpResponse response = httpexecutor.execute(request, conn, context);
httpexecutor.postProcess(response, httpproc, context);
// do something useful with the response
if (!connStrategy.keepAlive(response, context)) {
conn.close();
} else {
// Connection could be kept alive
}
} finally {
conn.close();
}
}
我相信其他 HTTP 库也是如此