Java HttpPost请求基于apache的httpclient

<span style="font-family: Arial, Helvetica, sans-serif;">/**</span>
* 发送 post请求访问本地应用并根据传递参数不同返回不同结果
*/
public static void post(String url, List<BasicNameValuePair> formparams) {
// 创建默认的httpClient实例.
CloseableHttpClient httpclient = HttpClients.createDefault();


// 创建httppost
HttpPost httppost = new HttpPost(url);
// 创建参数队列


UrlEncodedFormEntity uefEntity;
try {
uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
httppost.setEntity(uefEntity);
System.out.println("executing request" + httppost.getURI());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
HttpEntity entity = response.getEntity();
if (entity != null) {
System.out.println("--------------------------------------");
System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));
System.out.println("--------------------------------------");
}
} finally {
response.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭连接,释放资源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

猜你喜欢

转载自blog.csdn.net/gsrkuang/article/details/51210660