public void post(String url, Map<String, String> params){
CloseableHttpClient httpClient = null ;
HttpPost httpPost = null ;
try {
httpClient = HttpClients.createDefault();
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout( 20000 ).setConnectTimeout( 20000 ).build();
httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);
List<NameValuePair> ps = new ArrayList<NameValuePair>();
for (String pKey : params.keySet()) {
ps.add( new BasicNameValuePair(pKey, params.get(pKey)));
}
httpPost.setEntity( new UrlEncodedFormEntity(ps));
CloseableHttpResponse response = httpClient.execute(httpPost);
HttpEntity httpEntity = response.getEntity();
System.out.println(EntityUtils.toString(httpEntity, "utf-8" ));
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (httpPost!= null ){
httpPost.releaseConnection();
}
if (httpClient!= null ){
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
|