httpclient调用方法

时间:2023-07-26 20:51:56
/**
 * 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;
}