首页 > 其他分享 >HttpClient在SpringBoot中的使用

HttpClient在SpringBoot中的使用

时间:2023-09-03 22:32:35浏览次数:39  
标签:String import org file 使用 new HttpClient response SpringBoot

一、简介

HttpClient是Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包。

HttpClient 是一个HTTP通信库、一个工具包,它只提供一个通用浏览器应用程序所期望的功能子集,与浏览器相比是没有界面的。

二、引入依赖

<!--httpclient-->
<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpclient</artifactId>
	<version>4.5.14</version>
</dependency>
<!--fastjson-->
<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>fastjson</artifactId>
	<version>1.2.83</version>
</dependency>
<!--lombok-->
<dependency>
	<groupId>org.projectlombok</groupId>
	<artifactId>lombok</artifactId>
</dependency>

三、创建测试实体

我们创建一个实体类用来接收HttpClient请求获取到的数据

package com.example.websocketdemo.bean;

import lombok.Data;

/**
 * @author qx
 * @date 2023/09/03
 * @desc 地址实体类
 */
@Data
public class Address {

    private String status;
    private String info;
    private String infocode;
    private String province;
    private String city;
    private String adcode;
    private String rectangle;

}

四、GET请求


    @Test
    void testGet() throws IOException {
        // 请求地址
        String url = "https://restapi.amap.com/v3/ip?key=0113a13c88697dcea6a445584d535837&ip=182.91.200.188";
        CloseableHttpClient client = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        // 执行get请求
        CloseableHttpResponse response = client.execute(httpGet);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            String json = EntityUtils.toString(response.getEntity());
            // 解析Json数据
            Address address = JSONObject.parseObject(json, Address.class);
            System.out.println(address);
        }
    }

执行测试方法后控制台输出:

Address(status=1, info=OK, infocode=10000, province=广西壮族自治区, city=桂林市, adcode=450300, rectangle=110.1648474,25.1596868;110.4296887,25.39682984)

五、POST请求

@Test
    void testPost() throws IOException {
        CloseableHttpClient client = HttpClients.createDefault();
        String url = "https://restapi.amap.com/v3/ip";
        HttpPost httpPost = new HttpPost(url);
        // 设置请求参数
        List<NameValuePair> pairList = new ArrayList<>();
        pairList.add(new BasicNameValuePair("key", "0113a13c88697dcea6a445584d535837"));
        pairList.add(new BasicNameValuePair("ip", "182.91.200.188"));
        httpPost.setEntity(new UrlEncodedFormEntity(pairList));

        CloseableHttpResponse response = client.execute(httpPost);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            String json = EntityUtils.toString(response.getEntity());
            Address address = JSONObject.parseObject(json, Address.class);
            System.out.println(address);
        }
    }

执行测试方法后控制台输出:

Address(status=1, info=OK, infocode=10000, province=广西壮族自治区, city=桂林市, adcode=450300, rectangle=110.1648474,25.1596868;110.4296887,25.39682984)

六、注意事项

为防止请求数据乱码,我们可以主动设置编码。

 String json = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);

七、发送文件

引入依赖:

 <!--如果需要灵活的传输文件,引入此依赖后会更加方便-->
<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpmime</artifactId>
	<version>4.5.5</version>
</dependency>

测试:

我们先创建一个用于文件上传的请求方法

package com.example.websocketdemo.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author qx
 * @date 2023/09/03
 * @desc 文件上传控制器
 */
@RestController
public class FileController {

    @PostMapping("/upload")
    public String testFile(@RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return "文件不存在";
        }
        // 图片保存地址
        String path = "D:" + File.separator + "test.jpg";
        file.transferTo(new File(path));
        return "保存成功";
    }
}

然后我们在单元测试类中添加上传文件的操作。

@Test
    void testFile() throws IOException {
        CloseableHttpClient client = HttpClients.createDefault();
        // 图片上传请求地址
        HttpPost httpPost = new HttpPost("http://localhost:8081/upload");
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        String fileKey = "file";
        // 图片源路径
        File file = new File("C:/Users/Administrator/Desktop/0017029587773424_b.jpg");
        multipartEntityBuilder.addBinaryBody(fileKey, file);
        HttpEntity httpEntity = multipartEntityBuilder.build();
        httpPost.setEntity(httpEntity);

        CloseableHttpResponse response = client.execute(httpPost);
        if (response.getEntity() != null) {
            String responseStr = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
            System.out.println(responseStr);
        }
    }

启动程序和执行单元测试方法后,我们在控制台看到了控制器返回的数据。

保存成功

我们也在目的地址发现了我们新增的图片。

HttpClient在SpringBoot中的使用_上传文件


标签:String,import,org,file,使用,new,HttpClient,response,SpringBoot
From: https://blog.51cto.com/u_13312531/7343627

相关文章

  • OD动调之脱壳:使用ESP定律寻找
    OD动调之脱壳:使用ESP定律寻找usingODF8siglestepUntilstopThendatawindowfollow!Block!thenF9!Jmp->oep401171Youcanunpackupx!......
  • 日常使用vscode开发flutter相关的插件
    简介这里整理了日常使用vscode开发flutter相关的插件,也有部分通用类型的插件Flutter&Dart这2个是flutter官方插件,开发flutter装机必备,不用多说。AwesomeFlutterSnippetsAwesomeFlutterSnippetsisacollectionsnippetsandshortcutsforcommonlyusedFlutterfunction......
  • java语言B/S医院HIS系统【springboot】
     医院云HIS全称为基于云计算的医疗卫生信息系统(Cloud-BasedHealthcareInformationSystem),是运用云计算、大数据、物联网等新兴信息技术,按照现代医疗卫生管理要求,在一定区域范围内以数字化形式提供医疗卫生行业数据收集、存储、传递、处理的业务和技术平台,实现区域内医疗卫生......
  • 外观模式:简化复杂子系统的访问与使用
    文章目录1.简介2.外观模式的基本结构3.外观模式的实现步骤4.外观模式的应用与实例4.1图形界面库的外观模式应用4.2文件压缩与解压缩的外观模式应用4.3订单处理系统的外观模式应用5.外观模式的优缺点5.1优点5.2缺点6.总结1.简介外观模式是一种结构型设计模式,它提供了......
  • Vue2.0 使用wangEditor(富文本编辑器)
     1、安装npminstallwangeditor--save2、页面中使用2.1定义容器<divid="content"></div>2.2引用wangeditor//引入wangeditorimportwangEditorfrom"wangeditor";2.3创建实例,调用它的方法,使页面中呈现富文本编辑在mouted()勾子函数中操作mounted(){......
  • OpenGL入门——使用EBO绘制三角形
    上一节OpenGL入门——第一个三角形(1)-一只小瓶子-博客园(cnblogs.com)介绍了opengl怎么使用VAO和VBO绘制一个三角形这一节介绍一下使用EBO绘制 元素缓冲对象(ElementBufferObject,EBO),也叫索引缓冲对象(IndexBufferObject,IBO)。为什么会需要用到元素缓冲对象呢?因为上......
  • 9-3|使用Python的scikit-learn库来训练一个逻辑回归模型,检测句子是否含有侮辱性内容:
    当然可以。以下是一个简单的例子,使用Python的`scikit-learn`库来训练一个逻辑回归模型,检测句子是否含有侮辱性内容:```pythonfromsklearn.feature_extraction.textimportTfidfVectorizerfromsklearn.linear_modelimportLogisticRegressionfromsklearn.model_selectionim......
  • shell命令概述 Shell作用:命令解释器 介于操作系统内核与用户之间,负责解释命令行 获得
    Logo共40408字发布文章 草稿箱 1目录shell命令概述获得命令帮助Linux命令行的格式文件和目录管理Bash的命令历史Bash的命令别名重定向vim文本编辑器vim编辑器的工作模式命令模式中的基本操作末行模式中的基本操作用户和组账号概述用户账号文件——password用户账号文件——shadow......
  • shell命令概述 Shell作用:命令解释器 介于操作系统内核与用户之间,负责解释命令行 获得
    Logo共40408字发布文章 草稿箱 1目录shell命令概述获得命令帮助Linux命令行的格式文件和目录管理Bash的命令历史Bash的命令别名重定向vim文本编辑器vim编辑器的工作模式命令模式中的基本操作末行模式中的基本操作用户和组账号概述用户账号文件——password用户账号文件——shadow......
  • shell命令概述 Shell作用:命令解释器 介于操作系统内核与用户之间,负责解释命令行 获得
    Logo共40408字发布文章 草稿箱 1目录shell命令概述获得命令帮助Linux命令行的格式文件和目录管理Bash的命令历史Bash的命令别名重定向vim文本编辑器vim编辑器的工作模式命令模式中的基本操作末行模式中的基本操作用户和组账号概述用户账号文件——password用户账号文件——shadow......