写点什么

HttpClient 工具类

作者:Java高工P7
  • 2021 年 11 月 11 日
  • 本文字数:4866 字

    阅读完需:约 16 分钟

6.2 编写 spring-boot 启动类

/**


  • Description: springboot 启动类

  • @author JourWon

  • @date Created on 2018 年 4 月 19 日


*/


@SpringBootApplication


public class Application {


public static void main(String[] args) {


SpringApplication.run(Application.class, args);


}


}

6.3 编写 get 和 post 请求测试 controller

/**


  • Description: get 和 post 请求测试 controller

  • @author JourWon

  • @date Created on 2018 年 4 月 19 日


*/


@RestController


@RequestMapping("/hello")


public class HelloWorldController {


@GetMapping("/get")


public String get() throws InterruptedException {


return "get 无参请求成功";


}


@GetMapping("/getWithParam")


public String getWithParam(@RequestParam String message) {


return "get 带参请求成功,参数 message: " + message;


}


@PostMapping("/post")


public String post(@RequestHeader("User-Agent") String userAgent,


@RequestHeader("Accept") String accept,


@RequestHeader("Accept-Language") String acceptLanguage,


@RequestHeader("Accept-Encoding") String acceptEncoding,


@RequestHeader("Cookie") String cookie,


@RequestHeader("Connection") String conn) {


// 打印请求头信息


System.out.println("Cookie = " + cookie);


System.out.println("Connection = " + conn);


System.out.println("Accept = " + accept);


System.out.println("Accept-Language = " + acceptLanguage);


System.out.println("Accept-Encoding = " + acceptEncoding);


System.out.println("User-Agent = " + userAgent);


return "post 无参请求成功";


}


@PostMapping("/postWithParam")


public String postWithParam(@RequestParam String code, @RequestParam String message) {


return "post 带参请求成功,参数 code: " + code + ",参数 message: " + message;


}


}

6.4 创建 httpClient 响应结果对象

/**


  • Description: 封装 httpClient 响应结果

  • @author JourWon

  • @date Created on 2018 年 4 月 19 日


*/


public class HttpClientResult implements Serializable {


/**


  • 响应状态码


*/


private int code;


/**


  • 响应数据


*/


private String content;


}

6.5 重点,编写 httpclient 工具类

/**


  • Description: httpClient 工具类

  • @author JourWon

  • @date Created on 2018 年 4 月 19 日


*/


public class HttpClientUtils {


// 编码格式。发送编码格式统一用 UTF-8


private static final String ENCODING = "UTF-8";


// 设置连接超时时间,单位毫秒。


private static final int CONNECT_TIMEOUT = 6000;


// 请求获取数据的超时时间(即响应时间),单位毫秒。


private static final int SOCKET_TIMEOUT = 6000;


/**


  • 发送 get 请求;不带请求头和请求参数

  • @param url 请求地址

  • @return

  • @throws Exception


*/


public static HttpClientResult doGet(String url) throws Exception {


return doGet(url, null, null);


}


/**


  • 发送 get 请求;带请求参数

  • @param url 请求地址

  • @param params 请求参数集合

  • @return

  • @throws Exception


*/


public static HttpClientResult doGet(String url, Map<String, String> params) throws Exception {


return doGet(url, null, params);


}


/**


  • 发送 get 请求;带请求头和请求参数

  • @param url 请求地址

  • @param headers 请求头集合

  • @param params 请求参数集合

  • @return

  • @throws Exception


*/


public static HttpClientResult doGet(String url, Map<String, String> headers, Map<String, String> params) throws Exception {


// 创建 httpClient 对象


CloseableHttpClient httpClient = HttpClients.createDefault();


// 创建访问的地址


URIBuilder uriBuilder = new URIBuilder(url);


if (params != null) {


Set<Entry<String, String>> entrySet = params.entrySet();


for (Entry<String, String> entry : entrySet) {


uriBuilder.setParameter(entry.getKey(), entry.getValue());


}


}


// 创建 http 对象


HttpGet httpGet = new HttpGet(uriBuilder.build());


/**


  • setConnectTimeout:设置连接超时时间,单位毫秒。

  • setConnectionRequestTimeout:设置从 connect Manager(连接池)获取 Connection

  • 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。

  • setSocketTimeout:请求获取数据的超时时间(即响应时间),单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。


*/


RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();


httpGet.setConfig(requestConfig);


// 设置请求头


packageHeader(headers, httpGet);


// 创建 httpResponse 对象


CloseableHttpResponse httpResponse = null;


try {


// 执行请求并获得响应结果


return getHttpClientResult(httpResponse, httpClient, httpGet);


} finally {


// 释放资源


release(httpResponse, httpClient);


}


}


/**


  • 发送 post 请求;不带请求头和请求参数

  • @param url 请求地址

  • @return

  • @throws Exception


*/


public static HttpClientResult doPost(String url) throws Exception {


return doPost(url, null, null);


}


/**


  • 发送 post 请求;带请求参数

  • @param url 请求地址

  • @param params 参数集合

  • @return

  • @throws Exception


*/


public static HttpClientResult doPost(String url, Map<String, String> params) throws Exception {


return doPost(url, null, params);


}


/**


  • 发送 post 请求;带请求头和请求参数

  • @param url 请求地址

  • @param headers 请求头集合

  • @param params 请求参数集合

  • @return

  • @throws Exception


*/


public static HttpClientResult doPost(String url, Map<String, String> headers, Map<String, String> params) throws Exception {


// 创建 httpClient 对象


CloseableHttpClient httpClient = HttpClients.createDefault();


// 创建 http 对象


HttpPost httpPost = new HttpPost(url);


/**


  • setConnectTimeout:设置连接超时时间,单位毫秒。

  • setConnectionRequestTimeout:设置从 connect Manager(连接池)获取 Connection

  • 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。

  • setSocketTimeout:请求获取数据的超时时间(即响应时间),单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。


*/


RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();


httpPost.setConfig(requestConfig);


// 设置请求头


/*httpPost.setHeader("Cookie", "");


httpPost.setHeader("Connection", "keep-alive");


httpPost.setHeader("Accept", "application/json");


httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.9");


httpPost.setHeader("Accept-Encoding", "gzip, deflate, br");


httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");*/


packageHeader(headers, httpPost);


// 封装请求参数


packageParam(params, httpPost);


// 创建 httpResponse 对象


CloseableHttpResponse httpResponse = null;


try {


// 执行请求并获得响应结果


return getHttpClientResult(httpResponse, httpClient, httpPost);


} finally {


// 释放资源


release(httpResponse, httpClient);


}


}


/**


  • 发送 put 请求;不带请求参数

  • @param url 请求地址

  • @param params 参数集合

  • @return

  • @throws Exception


*/


public static HttpClientResult doPut(String url) throws Exception {


return doPut(url);


}


/**


  • 发送 put 请求;带请求参数

  • @param url 请求地址

  • @param params 参数集合

  • @return

  • @throws Exception


*/


public static HttpClientResult doPut(String url, Map<String, String> params) throws Exception {


CloseableHttpClient httpClient = HttpClients.createDefault();


HttpPut httpPut = new HttpPut(url);


RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();


httpPut.s


【一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义】
浏览器打开:qq.cn.hn/FTf 免费领取
复制代码


etConfig(requestConfig);


packageParam(params, httpPut);


CloseableHttpResponse httpResponse = null;


try {


return getHttpClientResult(httpResponse, httpClient, httpPut);


} finally {


release(httpResponse, httpClient);


}


}


/**


  • 发送 delete 请求;不带请求参数

  • @param url 请求地址

  • @param params 参数集合

  • @return

  • @throws Exception


*/


public static HttpClientResult doDelete(String url) throws Exception {


CloseableHttpClient httpClient = HttpClients.createDefault();


HttpDelete httpDelete = new HttpDelete(url);


RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();


httpDelete.setConfig(requestConfig);


CloseableHttpResponse httpResponse = null;


try {


return getHttpClientResult(httpResponse, httpClient, httpDelete);


} finally {


release(httpResponse, httpClient);


}


}


/**


  • 发送 delete 请求;带请求参数

  • @param url 请求地址

  • @param params 参数集合

  • @return

  • @throws Exception


*/


public static HttpClientResult doDelete(String url, Map<String, String> params) throws Exception {


if (params == null) {


params = new HashMap<String, String>();


}


params.put("_method", "delete");


return doPost(url, params);


}


/**


  • Description: 封装请求头

  • @param params

  • @param httpMethod


*/


public static void packageHeader(Map<String, String> params, HttpRequestBase httpMethod) {


// 封装请求头


if (params != null) {


Set<Entry<String, String>> entrySet = params.entrySet();


for (Entry<String, String> entry : entrySet) {


// 设置到请求头到 HttpRequestBase 对象中


httpMethod.setHeader(entry.getKey(), entry.getValue());


}


}


}


/**


  • Description: 封装请求参数

  • @param params

  • @param httpMethod

  • @throws UnsupportedEncodingException


*/


public static void packageParam(Map<String, String> params, HttpEntityEnclosingRequestBase httpMethod)


throws UnsupportedEncodingException {


// 封装请求参数


if (params != null) {


List<NameValuePair> nvps = new ArrayList<NameValuePair>();


Set<Entry<String, String>> entrySet = params.entrySet();


for (Entry<String, String> entry : entrySet) {


nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));


}


// 设置到请求的 http 对象中


httpMethod.setEntity(new UrlEncodedFormEntity(nvps, ENCODING));


}


}


/**


  • Description: 获得响应结果

  • @param httpResponse

  • @param httpClient

  • @param httpMethod

  • @return

  • @throws Exception


*/


public static HttpClientResult getHttpClientResult(CloseableHttpResponse httpResponse,


CloseableHttpClient httpClient, HttpRequestBase httpMethod) throws Exception {


// 执行请求


httpResponse = httpClient.execute(httpMethod);


// 获取返回结果


if (httpResponse != null && httpResponse.getStatusLine() != null) {


String content = "";


if (httpResponse.getEntity() != null) {


content = EntityUtils.toString(httpResponse.getEntity(), ENCODING);


}


return new HttpClientResult(httpResponse.getStatusLine().getStatusCode(), content);


}


return new HttpClientResult(HttpStatus.SC_INTERNAL_SERVER_ERROR);


}


/**


  • Description: 释放资源

  • @param httpResponse

  • @param httpClient

  • @throws IOException


*/


public static void release(CloseableHttpResponse httpResponse, CloseableHttpClient httpClient) throws IOException {


// 释放资源


if (httpResponse != null) {


httpResponse.close();


}


if (httpClient != null) {


httpClient.close();


}


}


}

用户头像

Java高工P7

关注

还未添加个人签名 2021.11.08 加入

还未添加个人简介

评论

发布
暂无评论
HttpClient工具类