gpt4 book ai didi

java - 如何在没有管理器的情况下使用apache HttpClient?

转载 作者:行者123 更新时间:2023-12-02 13:34:12 25 4
gpt4 key购买 nike

虽然 HttpClient 的正常使用工作正常,但我很难理解连接管理器部分。BasicHttpClientConnectionManager 和 PoolingHttpClientConnectionManager 似乎都不能满足我的用例。我在 JEE 应用程序服务器中运行并使用 HttpClient 来使用其余服务。

来自documentation :

BasicHttpClientConnectionManager is a simple connection manager that maintains only one connection at a time. [...] This connection manager implementation should be used inside an EJB container.

但我想做一些池化,最好是我自己的池化(例如 JCA 适配器)。我想简单地创建一个 HttpClient 并拥有自己的单独的 HttpClient 池,而无需连接管理器。有什么建议或解决方案吗?

最佳答案

使用 HttpClient 确实无法做到这一点,但可以使用 HttpCore,HttpClient 所基于的传输工具包

public static void main(String[] args) throws Exception {
HttpProcessor httpproc = HttpProcessorBuilder.create()
.add(new RequestContent())
.add(new RequestTargetHost())
.add(new RequestConnControl())
.add(new RequestUserAgent("Test/1.1"))
.add(new RequestExpectContinue(true)).build();

HttpRequestExecutor httpexecutor = new HttpRequestExecutor();

HttpCoreContext coreContext = HttpCoreContext.create();
HttpHost host = new HttpHost("localhost", 8080);
coreContext.setTargetHost(host);

DefaultBHttpClientConnection conn = new DefaultBHttpClientConnection(8 * 1024);
ConnectionReuseStrategy connStrategy = DefaultConnectionReuseStrategy.INSTANCE;

try {

String[] targets = {
"/",
"/servlets-examples/servlet/RequestInfoExample",
"/somewhere%20in%20pampa"};

for (int i = 0; i < targets.length; i++) {
if (!conn.isOpen()) {
Socket socket = new Socket(host.getHostName(), host.getPort());
conn.bind(socket);
}
BasicHttpRequest request = new BasicHttpRequest("GET", targets[i]);
System.out.println(">> Request URI: " + request.getRequestLine().getUri());

httpexecutor.preProcess(request, httpproc, coreContext);
HttpResponse response = httpexecutor.execute(request, conn, coreContext);
httpexecutor.postProcess(response, httpproc, coreContext);

System.out.println("<< Response: " + response.getStatusLine());
System.out.println(EntityUtils.toString(response.getEntity()));
System.out.println("==============");
if (!connStrategy.keepAlive(response, coreContext)) {
conn.close();
} else {
System.out.println("Connection kept alive...");
}
}
} finally {
conn.close();
}

示例代码取自here

关于java - 如何在没有管理器的情况下使用apache HttpClient?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43092079/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com