public class HttpClientUtil {
public static String doPost(String url,Map<String,String> map,String charset){
HttpClient httpClient = null;
HttpPost httpPost = null;
String result = null;
try{
//with ssl certificate verification 带证书验证
System.setProperty("javax.net.ssl.trustStore","Path\\to\\javaKeyStore");
System.setProperty("javax.net.ssl.trustStorePassword","password");
httpClient = HttpClientBuilder.create()
//without ssl certificate verification 注释部分是不带证书验证
// .setSSLContext(sslContext)
// .setConnectionManager(
// new PoolingHttpClientConnectionManager(
// RegistryBuilder.<ConnectionSocketFactory>create()
// .register("http", PlainConnectionSocketFactory.INSTANCE)
// .register("https", new SSLConnectionSocketFactory(sslContext,
// NoopHostnameVerifier.INSTANCE))
// .build()
// ))
.build();
httpPost = new HttpPost(url);
//设置参数
List<NameValuePair> list = new ArrayList<NameValuePair>();
Iterator iterator = map.entrySet().iterator();
while(iterator.hasNext()){
Entry<String,String> elem = (Entry<String, String>) iterator.next();
list.add(new BasicNameValuePair(elem.getKey(),elem.getValue()));
}
if(list.size() > 0){
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,charset);
httpPost.setEntity(entity);
}
HttpResponse response = httpClient.execute(httpPost);
if(response != null){
HttpEntity resEntity = response.getEntity();
if(resEntity != null){
result = EntityUtils.toString(resEntity,charset);
}
}
}catch(Exception ex){
ex.printStackTrace();
}
return result;
}
}