httpclient调用方法

/**
 * GET请求
 * 
 * @param url
 *            请求url,参数拼在请求串中
 */
public static String get(String url) {
String responseContent = null;
// 创建默认的httpClient实例.
CloseableHttpClient httpclient = HttpClients.createDefault();
CloseableHttpResponse response = null;
HttpGet httpGet = new HttpGet(url);
Logger.getRootLogger().info("--------------------------------------------");
Logger.getRootLogger().info("GET " + httpGet.getURI());
// 执行get请求.
try {
response = httpclient.execute(httpGet);
HttpEntity entity = response.getEntity();
// 打印响应状态
Logger.getRootLogger().info(response.getStatusLine());
if (entity != null) {
responseContent = EntityUtils.toString(entity);
// 打印响应内容
Logger.getRootLogger().info("Response content: "+ responseContent);
Logger.getRootLogger().info("--------------------------------------------");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpclient.close();
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return responseContent;
 
}
 
/**
 * 
 * @param url
 * @param paramMap
 */
public static String post(String url, Map<String, String> paramMap) {
String responseContent = null;
// 创建默认的httpClient实例.
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建httppost
HttpPost httppost = new HttpPost(url);
Logger.getRootLogger().info("--------------------------------------------");
Logger.getRootLogger().info("POST " + httppost.getURI());
// 创建参数队列
List<BasicNameValuePair> formparams = new ArrayList<BasicNameValuePair>();
if (paramMap != null) {
Set<String> key = paramMap.keySet();
for (Iterator<String> it = key.iterator(); it.hasNext();) {
String paramKey = (String) it.next();
formparams.add(new BasicNameValuePair(paramKey, paramMap
.get(paramKey)));
Logger.getRootLogger().info(paramKey+" = "+paramMap.get(paramKey));
}
}
 
UrlEncodedFormEntity uefEntity;
try {
uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
httppost.setEntity(uefEntity);
CloseableHttpResponse response = httpclient.execute(httppost);
try {
HttpEntity entity = response.getEntity();
Logger.getRootLogger().info(response.getStatusLine());
if (entity != null) {
responseContent = EntityUtils.toString(entity, "UTF-8");
Logger.getRootLogger().info("Response content: "+ responseContent);
Logger.getRootLogger().info("--------------------------------------------");
}
} 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();
}
}
return responseContent;
}

转载于:https://www.cnblogs.com/yanduanduan/p/4882484.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值