<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.5</version> </dependency>
public class GetUtils {
//无参方式
public void get(String url) {
getWithParams(url, new HashMap<>());
}
//有参方式
public void getWithParams(String url, Map<String, Object> params) {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
CloseableHttpResponse response = null;
try {
// 建立Get请求
url = joinParam(url, params);
HttpGet httpGet = new HttpGet(url);
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(2000) //服务器响应超时时间
.setConnectTimeout(2000) //链接服务器超时时间
.build();
httpGet.setConfig(requestConfig);
// 由客户端执行(发送)Get请求
response = httpClient.execute(httpGet);
// 从响应模型中获取响应实体
HttpEntity responseEntity = response.getEntity();
System.out.println("响应状态为:" + response.getStatusLine());
if (responseEntity != null) {
System.out.println("响应内容长度为:" + responseEntity.getContentLength());
System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// 释放资源
if (httpClient != null) {
httpClient.close();
}
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static String joinParam(String url, Map<String, Object> params) {
if (params == null || params.size() == 0) {
return url;
}
StringBuilder urlBuilder = new StringBuilder(url);
urlBuilder.append("?");
int counter = 0;
for (Map.Entry<String,Object> entry : params.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (key == null) {
continue;
}
if (counter == 0) {
urlBuilder.append(key).append("=").append(value);
} else {
urlBuilder.append("&").append(key).append("=").append(value);
}
counter++;
}
return urlBuilder.toString();
}
}
post请求有两种方式传参,一种是普通参数,一种是对象参数。普通参数传参方式和上面的get请求相同,对象参数须要使用setEntity()方法设置,同时须要指定请求的content-typegit
如下两段代码均为对象方式传参github
public class PostUtils { public void post(String url) { postWithParams(url, new HashMap<>()); } public void postWithParams(String url, Map<String, String> params) { List<NameValuePair> pairs = generatePairs(params); CloseableHttpClient httpClient = HttpClientBuilder.create().build(); CloseableHttpResponse response = null; try { HttpPost httpPost = new HttpPost(url); RequestConfig requestConfig = RequestConfig.custom() .setSocketTimeout(2000) //服务器响应超时时间 .setConnectTimeout(2000) //链接服务器超时时间 .build(); httpPost.setConfig(requestConfig); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs, "utf-8"); httpPost.setEntity(entity); httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded"); // 由客户端执行(发送)请求 response = httpClient.execute(httpPost); System.out.println("响应状态为:" + response.getStatusLine()); // 从响应模型中获取响应实体 HttpEntity responseEntity = response.getEntity(); if (responseEntity != null) { System.out.println("响应内容长度为:" + responseEntity.getContentLength()); System.out.println("响应内容为:" + EntityUtils.toString(responseEntity)); } } catch (Exception e) { e.printStackTrace(); } finally { try { // 释放资源 if (httpClient != null) { httpClient.close(); } if (response != null) { response.close(); } } catch (IOException e) { e.printStackTrace(); } } } private List<NameValuePair> generatePairs(Map<String, String> params) { if (params == null || params.size() == 0) { return Collections.emptyList(); } List<NameValuePair> pairs = new ArrayList<>(); for (Map.Entry<String,String> entry : params.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); if (key == null) { continue; } pairs.add(new BasicNameValuePair(key, value)); } return pairs; } }
public void postWithParams(String url, UserEntity userEntity) { CloseableHttpClient httpClient = HttpClientBuilder.create().build(); CloseableHttpResponse response = null; try { HttpPost httpPost = new HttpPost(url); RequestConfig requestConfig = RequestConfig.custom() .setSocketTimeout(2000) //服务器响应超时时间 .setConnectTimeout(2000) //链接服务器超时时间 .build(); httpPost.setConfig(requestConfig); StringEntity entity = new StringEntity(JSON.toJSONString(userEntity), "utf-8");//也能够直接使用JSONObject httpPost.setEntity(entity); httpPost.setHeader("Content-Type", "application/json;charset=utf8"); // 由客户端执行(发送)请求 response = httpClient.execute(httpPost); System.out.println("响应状态为:" + response.getStatusLine()); // 从响应模型中获取响应实体 HttpEntity responseEntity = response.getEntity(); if (responseEntity != null) { System.out.println("响应内容长度为:" + responseEntity.getContentLength()); System.out.println("响应内容为:" + EntityUtils.toString(responseEntity)); } } catch (Exception e) { e.printStackTrace(); } finally { try { // 释放资源 if (httpClient != null) { httpClient.close(); } if (response != null) { response.close(); } } catch (IOException e) { e.printStackTrace(); } } }
提示:网上有不少开源的http工具类,Github上Star很是多的一个HttpClient的工具类是httpclientutil,该工具类的编写者封装了不少功能在里面,若是apache
不是有什么特殊的需求的话,彻底能够直接使用该工具类。使用方式很简单,可详见https://github.com/Arronlong/httpclientutiljson