pom.xml
<!-- httpclient dependency -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
自定义HttpUitl工具类
public class HttpUtil {
/**
* 通过get请求获取响应报文
* @param uri 请求路径
* @param paramMap 请求参数
* @return 字符串格式的响应报文
* @throws ClientProtocolException HttpClient定义的客户端协议异常
* @throws IOException 读写异常
* @throws URISyntaxException URI格式异常
*/
public static String getGet(String uri , Map<String, Object> paramMap) throws ClientProtocolException, IOException, URISyntaxException {
CloseableHttpClient client = HttpClients.createDefault();
URIBuilder uriBuilder = new URIBuilder(uri);
if(paramMap != null) {
//遍历参数集合并添加到uriBuilder当中
for (String key : paramMap.keySet()) {
uriBuilder.setParameter(key, String.valueOf(paramMap.get(key)));
}
}
HttpGet httpGet = new HttpGet(uriBuilder.build());
//请求uri
CloseableHttpResponse response = client.execute(httpGet);
//获取响应的状态码,200为响应成功
int statusCode = response.getStatusLine().getStatusCode();
String responseStr = null;
if(statusCode == 200) {
//获取响应实体对象
HttpEntity entity = response.getEntity();
//通过EntityUtil工具类转换响应报文
responseStr = EntityUtils.toString(entity,"UTF-8");
}else {
responseStr = "NO RESPONSE BODY!";
}
response.close();
client.close();
return responseStr;
}
/**
* 通过post请求获取响应报文
* @param uri 请求路径
* @param paramMap 请求参数
* @return 字符串格式的响应报文
* @throws Exception 异常
*/
public static String getPost(String uri , Map<String, Object> paramMap) throws Exception {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(uri);
//创建参数对象集合
List<NameValuePair> paramList = new ArrayList<NameValuePair>();
if(paramMap != null) {
//遍历并添加请求参数到集合中
for(String key : paramMap.keySet()) {
paramList.add(new BasicNameValuePair(key, String.valueOf(paramMap.get(key))));
}
}
//创建Entity对象
StringEntity stringEntity = new UrlEncodedFormEntity(paramList , "UTF-8");
//为post请求添加entity对象
httpPost.setEntity(stringEntity);
//请求uri
CloseableHttpResponse response = client.execute(httpPost);
//获取响应的状态吗,200为响应成功
int statusCode = response.getStatusLine().getStatusCode();
String responseStr = null;
if(statusCode == 200) {
//获取响应实体对象
HttpEntity entity = response.getEntity();
//通过EntityUtil工具类转换响应报文
responseStr = EntityUtils.toString(entity , "UTF-8");
} else {
responseStr = "NO RESPONSE BODY!";
}
response.close();
client.close();
return responseStr;
}
}
单元测试
@Test
public void two() throws ClientProtocolException, IOException, URISyntaxException {
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("wd", "json");
String resultStr = HttpUtil.getGet("http://www.baidu.com/s", paramMap);
System.out.println(resultStr);
}
@Test
public void three() throws Exception {
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("username", "张三");
paramMap.put("password", "这是一个经过MD5加密的密码");
String resultStr = HttpUtil.getPost("http://127.0.0.1:8080/springmvcTemplate/One/two.json", paramMap);
System.out.println(resultStr);
}