java中使用Apache HttpClient傳送Http請求,並獲取返回結果
阿新 • • 發佈:2018-11-01
傳送http請求可以寫成一個工具類,HttpClient可以使用連線池建立,這樣的好處是我們可以自己定義一些配置,比如請求超時時間,最大連線數等等。
public class HttpUtil {
private static CloseableHttpClient httpClient;
private static RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(5000)
.setConnectTimeout(5000)
.setConnectionRequestTimeout(5000 )
.build();
static {
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
connManager.setMaxTotal(300);
connManager.setDefaultMaxPerRoute(300);
httpClient = HttpClients.custom().setConnectionManager(connManager).build();
}
// get請求
public static String get(String url) throws IOException {
HttpGet httpget = new HttpGet(url);
httpget.setConfig(requestConfig);
try (CloseableHttpResponse response = httpClient.execute(httpget)) {
return EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
}
}
// post請求
public static String post(String url, String json) throws IOException {
HttpEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(entity);
httpPost.setConfig(requestConfig);
try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
return EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
}
}
如果url後面需要接引數,那麼可以寫個方法將引數拼在url後面即可。