首先写一个方法,用于接收POST请求
public static String httpPost(String url, List<NameValuePair> list) {
log.info("the request info for url = {} is: {}", url);
// 创建默认的httpClient实例.
CloseableHttpClient httpClient = getDefaultHttpClient();
// 创建HttpPost
HttpPost httppost = new HttpPost(url);
try {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
httppost.setEntity(entity);
CloseableHttpResponse response = httpClient.execute(httppost);
HttpEntity respEntity = response.getEntity();
if (null != respEntity) {
String result = EntityUtils.toString(respEntity, "UTF-8");
log.info("the response info for url = {} is: {}", url, result);
return result;
}
} catch (IOException e) {
e.printStackTrace();
log.info("exception: ", e);
}
return "";
}
/**
* 获取传输普通http请求的HttpClient
*/
private static CloseableHttpClient initHttpClient() {
DnsResolver dnsResolver = new SystemDefaultDnsResolver();
// DnsResolver dnsResolver = getDnsResolver();
//需要通过以下代码声明对https连接支持
SSLContext sslcontext = null;
HttpClientBuilder httpClientBuilder = null;
CloseableHttpClient httpClient = null;
try {
sslcontext = SSLContexts.custom().loadTrustMaterial(null,
new TrustSelfSignedStrategy())
.build();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.getDefaultHostnameVerifier();
if (null != sslcontext) {
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslcontext, hostnameVerifier);
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", sslsf)
.build();
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(
socketFactoryRegistry, dnsResolver);
connManager.setMaxTotal(100);
connManager.setDefaultMaxPerRoute(10);
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(50 * 1000).setConnectTimeout(30 * 1000).build();
httpClientBuilder = HttpClients.custom();
httpClientBuilder.setConnectionTimeToLive(60L, TimeUnit.SECONDS);
httpClientBuilder.setConnectionManager(connManager);
httpClientBuilder.setDefaultRequestConfig(requestConfig);
httpClient = httpClientBuilder.build();
}
return httpClient;
}
调用上述POST方法的代码如下:
List<NameValuePair> list = new ArrayList<NameValuePair>();
list.add(new BasicNameValuePair("param1", "value1"));
list.add(new BasicNameValuePair("param2", "value2"));
String result = HttpUtilsForAdd.httpPost("http://beta83.baike.sogou.com/zyg/matchLemmaByTitle.v", list);