首页 > 编程语言 >Java HttpUtil 工具类 (使用 Apache HttpClient 包)

Java HttpUtil 工具类 (使用 Apache HttpClient 包)

时间:2022-09-30 16:46:13浏览次数:47  
标签:Java log new Apache import post null HttpUtil response

Java HttpUtil 工具类 (使用 Apache HttpClient 包)

第一步 引入包

 

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.13</version>
</dependency>

 

第二步 创建基础工具类

 

package io.supers.common.utils;

import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.util.Arrays;
import java.util.Map;

/**
 * @author guoc
 * @date 2022年08月16日 16:19
 */
@Slf4j
public class HttpUtil {

    public static JSONObject get(final String url, final Map<String, Object> params) {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        CloseableHttpResponse response = null;
        StringBuilder urlBuilder = new StringBuilder(url);
        urlBuilder.append("?");
        if (MapUtil.isNotEmpty(params)) {
            for (Map.Entry<String, Object> p : params.entrySet()) {
                urlBuilder.append(p.getKey()).append("=").append(p.getValue()).append("&");
            }
        }
        try {
            HttpGet httpGet = new HttpGet();
            httpGet.setURI(new URI(urlBuilder.substring(0, urlBuilder.length() - 1)));
            log.info("\nGET 地址为:" + httpGet.getURI().toString());
            response = httpClient.execute(httpGet);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            log.debug("\nGET 响应状态为:" + response.getStatusLine());
            if (responseEntity != null) {
                String entityStr = EntityUtils.toString(responseEntity);
                log.debug("\nGET 响应内容: " + entityStr);
                log.debug("\nGET 响应内容长度为:" + responseEntity.getContentLength());
                return JSON.parseObject(entityStr);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    
    public static JSONObject post(HttpPost httpPost) {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        CloseableHttpResponse response = null;
        try {
            log.info("\nPOST 地址为: " + httpPost.getURI().toString());
            log.info("\nPOST 请求头为: " + Arrays.toString(httpPost.getAllHeaders()));
            log.info("\nPOST 内容为: " + httpPost.getEntity());
            // 由客户端执行(发送)Post请求
            response = httpClient.execute(httpPost);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            log.debug("\nPOST 响应状态为:" + response.getStatusLine());
            if (responseEntity != null) {
                String entityStr = EntityUtils.toString(responseEntity);
                log.debug("\nPOST 响应内容: " + entityStr);
                log.debug("\nPOST 响应内容长度为:" + responseEntity.getContentLength());
                return JSON.parseObject(entityStr);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

}

 

基础工具类用到了 hutool包, alibaba 的 fastjson 包,以及lombok 包, 引用为

 

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.8.4.M1</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>${fastjson.version}</version>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>${lombok.version}</version>
</dependency>

 

基础工具类 提供了两个方法 get(url,params) 和 post(httpPost).

第三步 使用工具类

使用Get请求

例如, 需要请求地址 http://aaa.com/a/b?c=d&e=f ,代码示例为

 

String url = "http://aaa.com/a/b";
Map<String, Object> params = MapUtil.newHashMap();
params.put("c", "d");
params.put("e", "f");
JSONObject jsonObject = get(url, params);
System.out.println(jsonObject);

 

使用Post请求

例如,需要请求地址 https://bbb.com/c/d?e=f , 并且需要传入UTF-8编码JSON格式的requestbody( {"g":"h","i":"j"} ),代码示例为

 

HttpPost post = new HttpPost();
// 注意这里的地址 跟 get请求不同 需要把参数直接拼接起来 (一般post请求不带地址栏参数,但此工具方法也需要支持传地址栏参数)
post.setURI(URI.create("https://bbb.com/c/d?e=f"));
// 为确保接收端能接收到正确编码的 requestBody 尽量加上header 设置
post.setHeader(new BasicHeader("Content-Type", "application/json;charset=UTF-8"));
// 设置 StringEntity 时, 也需要设置编码, 此处的编码设置***非常重要***
post.setEntity(new StringEntity("{\"g\":\"h\",\"i\":\"j\"}", StandardCharsets.UTF_8));
JSONObject jsonObject = post(post);
System.out.println(jsonObject);

 

若是接收端接收的不是JSON格式的数据, 而是表单格式的 requestBody, 则代码需要改为

 

HttpPost post = new HttpPost();
// 注意这里的地址 跟 get请求不同 需要把参数直接拼接起来 (一般post请求不带地址栏参数,但此工具方法也需要支持传地址栏参数)
post.setURI(URI.create("https://bbb.com/c/d?e=f"));
post.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded"));
List<NameValuePair> pairs = CollUtil.newArrayList();
pairs.add(new BasicNameValuePair("g", "h"));
pairs.add(new BasicNameValuePair("i", "j"));
post.setEntity(new UrlEncodedFormEntity(pairs, StandardCharsets.UTF_8));
JSONObject jsonObject = post(post);
System.out.println(jsonObject);

 

 

标签:Java,log,new,Apache,import,post,null,HttpUtil,response
From: https://www.cnblogs.com/mlxs/p/16745361.html

相关文章

  • Java集合框架之List
    1.List集合概要2.Iterable接口1.概要2.重要方法forEach方法:对Collection集合中的每个对象进行消费List<Student>list=Stream.generate(()->newStudent("张......
  • Java线程池
    Java线程池线程池的执行过程当向线程池提交一个新的任务,线程池首先判断核心线程池的线程是否都在执行任务。如果不是,创建一个新的工作线程来执行任务。如果核心线程的......
  • 力扣500(java&python)-键盘行(简单)
    题目:给你一个字符串数组words,只返回可以使用在美式键盘同一行的字母打印出来的单词。键盘如下图所示。美式键盘中:第一行由字符"qwertyuiop"组成。第二行由字符"......
  • JAVA关键字修饰
    Java中,可以使用访问控制符来保护对类、变量、方法和构造方法的访问。Java支持4种不同的访问权限。default (即默认,什么也不写):在同一包内可见,不使用任何修饰符。使......
  • java 遍历目录 删除目录 判断是否为目录
    删除目录privatestaticbooleandeleteDir(Filefile){if(file==null||!file.exists()){System.out.println("deletefilesfail,fi......
  • Java GUI编程(二)Swing
    一,窗口 二,弹窗publicclassDialogDemoextendsJFrame{publicDialogDemo(){this.setVisible(true);this.setSize(700,500);thi......
  • java mail实现POP3协议收件的Oauth认证
    1.背景   有team使用了office365的国际版邮箱进行收发邮件,但是微软会在十月一后关闭基本身份认证,选择使用OAuth身份验证连接IMAP、POP或SMTP协议,微软给出了相......
  • Java:通过标记直接跳出嵌套的循环结构
    这是我在刷面试题的时候遇到的一个使用方法,之前甚至对这种方法闻所未闻,不禁感慨自己的才疏学浅。闲话少说,直接进入正题。具体的使用就是在需要跳出的循环结构前面加一个......
  • java支持的运算符以及作用
    java语言支持如下运算符,优先级使用括号(),算数运算符:+,-,*,/,%(取余运算,或模运算),++(自增),--(自减)赋值运算符:=inta=10(把10赋值给a)关系运算符:>,<,>=,<=,==(java里等......
  • JavaScript大文件(百M以上)的上传下载实现技术
    ​最近遇见一个需要上传超大大文件的需求,调研了七牛和腾讯云的切片分段上传功能,因此在此整理前端大文件上传相关功能的实现。在某些业务中,大文件上传是一个比较重要的交......