java 使用HttpClient发送@RequestBody类型的请求(解决中文乱码)

如何使用java发送参数以@RequestBody类型接收到的请求。如下使用java的HttpClient写一个样例

依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpcore</artifactId>
    <version>4.4.10</version>
</dependency>
 
<dependency>
    <groupId>commons-httpclient</groupId>
    <artifactId>commons-httpclient</artifactId>
    <version>3.1</version>
</dependency>
 
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.6</version>
</dependency>

 

1、接收部分代码

1
2
3
4
5
6
@RequestMapping("/test")
    public void getAccessToken(@RequestBody String jsonStr) {
 
        System.out.println("jsonStr:"+jsonStr);
 
    }

 2、HttpClient发送的方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public static String doPostRequestBody(String url, String jsonStr) {
        try {
            // 创建HttpClient实例
            HttpClient client = HttpClients.createDefault();
            // 创建HttpPost实例,指定URL
            HttpPost post = new HttpPost(url);
 
            // 设置请求头
            post.setHeader("Content-Type", "application/json; charset=UTF-8");
            post.setHeader("apiVersion", "v1");
 
            // 设置请求体
            StringEntity entity = new StringEntity(jsonStr, StandardCharsets.UTF_8);
            post.setEntity(entity);
            // 发送请求
            HttpResponse httpResponse = client.execute(post);
            // 获取响应输入流
            InputStream inStream = httpResponse.getEntity().getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, "UTF-8"));
            String line = null;
            StringBuilder result = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }
            // 打印响应内容
            System.out.println("Response: " + result.toString());
            return result.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

 3、等同于postMan中的调用

 

posted @   万笑佛  阅读(69)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
历史上的今天:
2023-12-27 python生成word文档
点击右上角即可分享
微信分享提示