HttpClient
博客地址:https://blog.csdn.net/justry_deng/article/details/81042379
HttpClientUtil封装的工具类
github:https://github.com/Arronlong/httpclientutil
HttpClient作者封装的工具类
GET无参工具类
package com.xiaomin.wechat.util;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
/**
* @author 晓敏
* @create 2019-11-15 10:22
*/
public class HttpGetUtil {
/**
* GET无参工具类
* @param url 接口地址
* @return 调用接口后返回的结果
*/
public static String doGet(String url){
String result="";
CloseableHttpResponse response=null;
// 1、获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
///2、创建Get请求
HttpGet httpGet = new HttpGet(url);
try {
// 3、由客户端执行(发送)Get请求
response = httpClient.execute(httpGet);
///4、从响应模型中获取响应实体
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity,"utf-8");//响应的内容进行编码
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(httpClient!=null){//关闭连接
httpClient.close();
}
if(response!=null){//关闭
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
}
测试结果:
@Test
public void fun2(){
String result = HttpGetUtil.doGet("http://localhost:8081/getfirst");
System.out.println(result);
}