java httpclient 连接池 代码
时间: 2023-10-17 14:22:15 浏览: 125
java 连接池源代码
3星 · 编辑精心推荐
很好,我明白你的要求了。以下是一个简单的Java HTTPClient连接池代码示例:
```
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
public class HttpUtils {
private static final int MAX_TOTAL_CONNECTIONS = 200;
private static final int MAX_ROUTE_CONNECTIONS = 20;
private static final int TIMEOUT = 3000;
private static CloseableHttpClient httpClient;
static {
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(MAX_TOTAL_CONNECTIONS);
cm.setDefaultMaxPerRoute(MAX_ROUTE_CONNECTIONS);
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(TIMEOUT)
.setConnectTimeout(TIMEOUT)
.setConnectionRequestTimeout(TIMEOUT)
.build();
httpClient = HttpClientBuilder.create()
.setDefaultRequestConfig(requestConfig)
.setConnectionManager(cm)
.build();
}
public static String doGet(String url) throws IOException {
HttpGet httpGet = new HttpGet(url);
return execute(httpClient, httpGet);
}
public static String doPost(String url, String body, ContentType contentType) throws IOException {
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new StringEntity(body, contentType));
return execute(httpClient, httpPost);
}
private static String execute(CloseableHttpClient client, HttpRequestBase request) throws IOException {
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
EntityUtils.consume(entity);
return result;
}
}
```
这里使用了Apache HttpComponents实现的Http客户端,并使用连接池技术来维护连接,以提高性能和可靠性。其中,最大连接数设置为200,每个路由最大连接数设置为20,超时时间设置为3秒。提供了简单的GET和POST请求方法,并支持指定内容类型。
阅读全文