在java后端发送HTTPClient请求

news2024/10/1 5:43:10

简介

  • HttpClient
  • 遵循http协议的客户端编程工具包
  • 支持最新的http协议

在这里插入图片描述
在这里插入图片描述

部分依赖自动传递依赖了HttpClient的jar包

  • 明明项目中没有引入 HttpClient 的Maven坐标,但是却可以直接使用HttpClient
  • 原因是:阿里云的sdk依赖中传递依赖了HttpClient的jar包

在这里插入图片描述

在这里插入图片描述

发送get请求

    @Test
    public void testGet() {
        // 创建HttpGet对象
        HttpGet httpGet = new HttpGet("http://localhost:8080/user/shop/status");
        // 创建HttpClient对象 用于发送请求
        // try-with-resources 语法 需要关闭的资源分别是 httpClient response
        try (CloseableHttpClient httpClient = HttpClients.createDefault();
             CloseableHttpResponse response = httpClient.execute(httpGet)) {
            // 获取响应状态码
            int statusCode = response.getStatusLine().getStatusCode();
            System.out.println("响应状态码:" + statusCode); //响应状态码:200
            // 获取响应数据
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity);
            System.out.println("响应数据:" + result); // 响应数据:{"code":1,"msg":null,"data":1}
        } catch (IOException e) {
            log.error("请求失败", e);
            e.printStackTrace();
        }
    }

发送post请求

    /**
     * 测试HttpClient 发送post请求 需要提前启动项目 不然请求不到
     */
    @Test
    public void testPost() {
        // 创建HttpPost对象
        HttpPost httpPost = new HttpPost("http://localhost:8080/admin/employee/login");
        // 这个请求是有请求体的
        // 使用JsonObject构建请求体  更加高效简洁
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("username", "admin");
        jsonObject.addProperty("password", "123456");
        // 将json对象转为字符串 并设置编码格式 设置传输的数据格式 使用构造器和set方法都是可以设置的
        StringEntity stringEntity = null;
        try {
            stringEntity = new StringEntity(jsonObject.toString());
            stringEntity.setContentEncoding("UTF-8");
            stringEntity.setContentType("application/json");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        // 设置请求体
        httpPost.setEntity(stringEntity);

        // 创建HttpClient对象 用于发送请求
        // try-with-resources 语法 需要关闭的资源分别是 httpClient response
        try (CloseableHttpClient httpClient = HttpClients.createDefault();
             CloseableHttpResponse response = httpClient.execute(httpPost)) {
            // 获取响应状态码
            int statusCode = response.getStatusLine().getStatusCode();
            System.out.println("响应状态码:" + statusCode); //响应状态码:200
            // 获取响应数据
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity);
            System.out.println("响应数据:" + result); // 响应数据:{"code":1,"msg":null,"data":{"id":1,"userName":"admin","name":"管理员","token":"eyJhbGciOiJIUzI1NiJ9.eyJlbXBJZCI6MSwiZXhwIjoxNzI4MzgwOTk5fQ.Rm7UWZbDEU_06DJLfegcP31n-9g8AB-Jxa-49Zw-ttM"}}
        } catch (IOException e) {
            log.error("请求失败", e);
            e.printStackTrace();
        }
    }

工具类

分装了一个工具类

  • 发送get请求
  • 使用form表单发送post请求
  • 使用json对象发送post请求
package com.sky.utils;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Http工具类
 */
@Slf4j
public class HttpClientUtil {

    static final int TIMEOUT_MSEC = 5 * 1000;
    public static final String UTF_8 = "utf-8";
    public static final String DEFAULT_CONTENT_TYPE = "application/json";
    public static final String LOG_ERR_TEMPLATE = "{}路径请求出错,错误详情如下";

    /**
     * 发送GET请求,返回字符串
     */
    public static String doGet(String url, Map<String, String> paramMap) throws URISyntaxException, IOException {
        String result = "";

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            URIBuilder builder = new URIBuilder(url);
            if (paramMap != null) {
                for (String key : paramMap.keySet()) {
                    builder.addParameter(key, paramMap.get(key));
                }
            }
            URI uri = builder.build();

            // 创建GET请求
            HttpGet httpGet = new HttpGet(uri);

            // 发送请求
            try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                // 判断响应状态
                if (response.getStatusLine().getStatusCode() == 200) {
                    result = EntityUtils.toString(response.getEntity(), UTF_8);
                }
            }
        } catch (Exception e) {
            // 日志记录
            logErr(url);
            throw e;
        }

        return result;
    }

    /**
     * 发送GET请求,返回JSONObject
     */
    public static JSONObject doGetJson(String url, Map<String, String> paramMap) throws URISyntaxException, IOException {
        JSONObject result = null;

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            URIBuilder builder = new URIBuilder(url);
            if (paramMap != null) {
                for (String key : paramMap.keySet()) {
                    builder.addParameter(key, paramMap.get(key));
                }
            }
            URI uri = builder.build();

            // 创建GET请求
            HttpGet httpGet = new HttpGet(uri);

            // 发送请求
            try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                // 判断响应状态
                if (response.getStatusLine().getStatusCode() == 200) {
                    String resultString = EntityUtils.toString(response.getEntity(), UTF_8);
                    result = JSONObject.parseObject(resultString);
                }
            }
        } catch (Exception e) {
            logErr(url);
            throw e;
        }

        return result;
    }



    /**
     * 发送POST请求,返回字符串 表单请求
     */
    public static String doPost(String url, Map<String, String> paramMap) throws IOException {
        String resultString = "";

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);

            // 创建参数列表
            if (paramMap != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (Map.Entry<String, String> param : paramMap.entrySet()) {
                    paramList.add(new BasicNameValuePair(param.getKey(), param.getValue()));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
                httpPost.setEntity(entity);
            }

            httpPost.setConfig(builderRequestConfig());

            // 执行http请求
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                resultString = EntityUtils.toString(response.getEntity(), UTF_8);
            }
        } catch (Exception e) {
            logErr(url);
            throw e;
        }

        return resultString;
    }

    /**
     * 发送POST请求,返回JSONObject 表单请求
     */
    public static JSONObject doPostJson(String url, Map<String, String> paramMap) throws IOException {
        JSONObject result = null;

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);

            // 创建参数列表
            if (paramMap != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (Map.Entry<String, String> param : paramMap.entrySet()) {
                    paramList.add(new BasicNameValuePair(param.getKey(), param.getValue()));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
                httpPost.setEntity(entity);
            }

            httpPost.setConfig(builderRequestConfig());

            // 执行http请求
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                String resultString = EntityUtils.toString(response.getEntity(), UTF_8);
                result = JSONObject.parseObject(resultString);
            }
        } catch (Exception e) {
            logErr(url);
            throw e;
        }

        return result;
    }

    /**
     * 发送POST请求,JSON格式数据,返回字符串 json请求
     */
    public static String doPost4Json(String url, Map<String, String> paramMap) throws IOException {
        String resultString = "";

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(url);

            if (paramMap != null) {
                // 构造json格式数据
                JSONObject jsonObject = new JSONObject();
                for (Map.Entry<String, String> param : paramMap.entrySet()) {
                    jsonObject.put(param.getKey(), param.getValue());
                }
                StringEntity entity = new StringEntity(jsonObject.toString(), UTF_8);
                // 设置请求编码
                entity.setContentEncoding(UTF_8);
                // 设置数据类型
                entity.setContentType(DEFAULT_CONTENT_TYPE);
                httpPost.setEntity(entity);
            }

            httpPost.setConfig(builderRequestConfig());

            // 执行http请求
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                resultString = EntityUtils.toString(response.getEntity(), UTF_8);
            }
        } catch (Exception e) {
            logErr(url);
            throw e;
        }

        return resultString;
    }

    /**
     * 发送POST请求,JSON格式数据,返回JSONObject json请求
     */
    public static JSONObject doPost4JsonReturnJson(String url, Map<String, String> paramMap) throws IOException {
        JSONObject result = null;

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(url);

            if (paramMap != null) {
                // 构造json格式数据
                JSONObject jsonObject = new JSONObject();
                for (Map.Entry<String, String> param : paramMap.entrySet()) {
                    jsonObject.put(param.getKey(), param.getValue());
                }
                StringEntity entity = new StringEntity(jsonObject.toString(), UTF_8);
                // 设置请求编码
                entity.setContentEncoding(UTF_8);
                // 设置数据类型
                entity.setContentType(DEFAULT_CONTENT_TYPE);
                httpPost.setEntity(entity);
            }

            httpPost.setConfig(builderRequestConfig());

            // 执行http请求
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                String resultString = EntityUtils.toString(response.getEntity(), UTF_8);
                result = JSONObject.parseObject(resultString);
            }
        } catch (Exception e) {
            logErr(url);
           throw e;
        }

        return result;
    }

    private static RequestConfig builderRequestConfig() {
        return RequestConfig.custom()
                .setConnectTimeout(TIMEOUT_MSEC)
                .setConnectionRequestTimeout(TIMEOUT_MSEC)
                .setSocketTimeout(TIMEOUT_MSEC).build();
    }


    /**
     * 日志报错
     * @param url 出错的URL
     */
    private static void logErr(String url) {
        log.error(LOG_ERR_TEMPLATE, url);
    }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2181631.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

HTB:Archetype[WriteUP]

使用OpenVPN连接HTB服务器并启动靶机 靶机IP&#xff1a;10.129.95.187 分配IP&#xff1a;10.10.16.22 1.Which TCP port is hosting a database server? 使用nmap对靶机进行扫描&#xff1a;nmap -sC -sV -T4 -Pn {TARGET_IP} 通过nmap扫描结果可见&#xff1a; 1433 端口用…

C++ | Leetcode C++题解之第448题找到所有数组中消失的数字

题目&#xff1a; 题解&#xff1a; class Solution { public:vector<int> findDisappearedNumbers(vector<int>& nums) {int n nums.size();for (auto& num : nums) {int x (num - 1) % n;nums[x] n;}vector<int> ret;for (int i 0; i < n;…

有效的字母异位词【字符串哈希】

题目 题解&#xff1a; 1.排序&#xff1a; #include<algorithm>class Solution{public:bool isAnagram(string s,string t){sort(s.begin(),s.end());sort(t.begin(),t.end());return st;} } 时间复杂度O(nlogn) 2.哈希表 #include<algorithm>int hash1[100]; …

旅游推荐|旅游推荐系统|基于Springboot+VUE的旅游推荐系统设计与实现(源码+数据库+文档)

旅游推荐系统 目录 基于java的旅游推荐系统设计与实现 一、前言 二、系统功能设计 三、系统实现 四、数据库设计 1、实体ER图 五、核心代码 六、论文参考 七、最新计算机毕设选题推荐 八、源码获取&#xff1a; 博主介绍&#xff1a;✌️大厂码农|毕设布道师&#xf…

B端:常见通用模块有哪些,CRM除了通用模块,有哪些个性模块?

我经常把B端系统的功能模块分为通用模块和个性模块&#xff0c;通用模块是大部分系统都具备的功能&#xff0c;通用模块员工、日程、审批、代办等等&#xff0c;就是OA&#xff0c;通用模块生产、订单、物料、车间、设备、成本等等就是MES&#xff0c;这么说大家都晓得了吧&…

【pytorch】pytorch入门5:最大池化层(Pooling layers )

文章目录 前言一、定义概念 缩写二、参数三、最大池化操作四、使用步骤总结参考文献 前言 使用 B站小土堆课程 一、定义概念 缩写 池化&#xff08;Pooling&#xff09;是深度学习中常用的一种操作&#xff0c;用于降低卷积神经网络&#xff08;CNN&#xff09;或循环神经网…

Vue diff 算法介绍

首先我们来了解一下&#xff1a;diff 是什么&#xff1f; 通俗的讲&#xff0c;diff 就是比较两棵树&#xff0c;render 会生成两颗树&#xff0c;一棵新树 newVnode&#xff0c;一棵旧树 oldVnode&#xff0c;然后两棵树进行对比更新找差异就是 diff&#xff0c;全称 differe…

【cpp/c++ summary 工具】 Hunter 包管理器

Hunter 是一个跨平台cpp包管理器,点击查看支持的所有包的列表。 查看cmake是否满足 查看cmake是否满足Hunter版本要求&#xff1a; ubuntuDESKTOP-D7DRBER:~/CODE/mycpp/hunter-simple-master$ cmake --version cmake version 3.16.3CMake suite maintained and supported b…

88E1111使用技巧

一、88E1111简介 88E1111这款芯片是Marvel公司的产品&#xff0c;算是早期产品&#xff0c;但是市面上通用量较高&#xff0c;目前仍在大量使用&#xff0c;当然该公司也推出新产品&#xff0c;如88E1512&#xff0c;后续会有续篇&#xff0c;本篇文章重点讲述88E1111。 88E1…

66 使用注意力机制的seq2seq_by《李沐:动手学深度学习v2》pytorch版

系列文章目录 文章目录 系列文章目录动机加入注意力总结代码定义注意力解码器训练小结练习 我们来真的看一下实际应用中&#xff0c;key&#xff0c;value&#xff0c;query是什么东西&#xff0c;但是取决于应用场景不同&#xff0c;这三个东西会产生变化。先将放在seq2seq这个…

使用 SSH 连接 Docker 服务器:IntelliJ IDEA 高效配置与操作指南

使用 SSH 连接 Docker 服务器&#xff1a;IntelliJ IDEA 高效配置与操作指南 本文详细介绍了如何在 2375 端口未开放的情况下&#xff0c;通过 SSH 连接 Docker 服务器并在 Idea 中进行开发。通过修改用户权限、生成密钥对以及配置 SSH 访问&#xff0c;用户可以安全地远程操作…

Ubuntu 系统崩了,如何把数据拷下来

问题描述&#xff1a; Linux系统中安装输入法后&#xff0c;重启后&#xff0c;导致系统无法进入&#xff0c;进入 recovery mode下的resume 也启动不了&#xff0c;所以决定将需要的东西复制到U盘 解决方案&#xff1a; 1.重启ubuntu&#xff0c;随即点按Esc进入grub菜单&am…

Linux shell脚本set -e的作用详解

文章目录 功能详细解释示例不使用 set -e 的情况总结 set -e 是一个用于控制脚本行为的命令&#xff0c;它的作用是&#xff1a; 功能 当脚本运行时&#xff0c;set -e 会确保一旦某个命令返回非零的退出状态&#xff08;即执行失败&#xff09;&#xff0c;整个脚本会立即停止…

Docker面试-24年

1、Docker 是什么&#xff1f; Docker一个开源的应用容器引擎&#xff0c;是实现容器技术的一种工具&#xff0c;让开发者可以打包他们的应用以及环境到一个镜像中&#xff0c;可以快速的发布到任何流行的操作系统上。 2、Docker的三大核心是什么? 镜像&#xff1a;Docker的…

在 Kali Linux 中安装 Impacket

步骤 1&#xff1a;更新系统 打开终端并确保你的系统是最新的&#xff1a; sudo apt update && sudo apt upgrade -y 步骤 2&#xff1a;安装依赖 在安装 Impacket 之前&#xff0c;你需要确保安装了 Python 和一些必要的依赖。通常&#xff0c;Kali 已经预装了 Pytho…

工作日志:el-table在无数据情况下,出现横向滚动条。

1、遇到一个警告。 原因&#xff1a;中的组件不能呈现动画的非元素根节点。 也就是说&#xff0c;Transition包裹的必须是一个单根的组件。 2、el-table在无数据情况下&#xff0c;出现横向滚动条&#xff0c;大概跟边框的设置有关系。 开始排查。 给.el-scrollbar加了一个…

Linux 线程同步

前言 上一期我们介绍了线程互斥&#xff0c;并通过加锁解决了多线程并发访问下的数据不一致问题&#xff01;本期我们来介绍一下同步问题&#xff01; 目录 前言 一、线程同步 • 线程同步的引入 • 同步的概念 理解同步和饥饿问题 • 条件变量 理解条件变量 • 同步…

TypeScript 算法手册 【数组基础知识】

文章目录 1. 数组简介1.1 数组定义1.2 数组特点 2. 数组的基本操作2.1 访问元素2.2 添加元素2.3 删除元素2.4 修改元素2.5 查找元素 3. 数组的常见方法3.1 数组的创建3.2 数组的遍历3.3 数组的映射3.4 数组的过滤3.5 数组的归约3.6 数组的查找3.7 数组的排序3.8 数组的反转3.9 …

AI写作赋能数据采集,开启无限可能性

由人工智能 AI 掀起的新一轮科技革命浪潮&#xff0c;正在不断推动社会进步、各行各业升级发展&#xff0c;深刻影响人们的生活方式&#xff0c;引领我们进入一个充满无限可能的新时代。 那么在数据采集方面&#xff0c;人工智能 AI 可以做什么呢&#xff1f; 下面是搜集网络…

开源在线表结构设计工具

Free, simple, and intuitive database design tool and SQL generator. drawDB在线体验 Discord X drawDB DrawDB is a robust and user-friendly database entity relationship (DBER) editor right in your browser. Build diagrams with a few clicks, export sql scri…