RPC(4):HttpClient实现RPC之POST请求

接上一篇博客RPC(3):HttpClient实现RPC之GET请求内容。

1 新建一个实体项目

新建项目httpclient_rpc_pojo

1.1 新建实体类

复制代码
package com.example.httpclientpojo;

import java.io.Serializable;
import java.util.Date;
import java.util.Objects;

public class User implements Serializable {
    private String name;
    private String password;
    private Date birth;

    public int getAge(){
        if(birth == null){
            return -1;
        }
        int birthYear = birth.getYear();
        int currentYear = new Date().getYear();
        return currentYear - birthYear;
    }
    public void setAge(int age){}

    public Date getBirth() {
        return birth;
    }

    public void setBirth(Date birth) {
        this.birth = birth;
    }

    @Override
    public String toString() {
        return "{\"name\":\""+name+"\", \"password\":\""+password+"\"}";
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        User user = (User) o;
        return Objects.equals(name, user.name) &&
                Objects.equals(password, user.password);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, password);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

2 修改服务项目

修改httpclient_rpc_server项目,在TestController中新增"使用请求体传递请求参数"方法。

复制代码
    // 使用请求体传递请求参数。
    @RequestMapping(value="/bodyParams", produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public String bodyParams(@RequestBody List<User> users){
        System.out.println(users);
        return users.toString();
    }

3 修改客户端项目

在TestHttpClient中新增方法如下:

复制代码
    public static void testPostNoParams() throws Exception{
        HttpClient client = HttpClients.createDefault();
        // 无参数Post请求
        HttpPost post = new HttpPost("http://localhost/test");
        HttpResponse response = client.execute(post);
        System.out.println(EntityUtils.toString(response.getEntity(), "UTF-8"));
    }

    public static void testPostParamswithTitle() throws Exception{
        HttpClient client = HttpClients.createDefault();
        // 有参数的Post请求
        // 请求头传递参数。和Get请求携带参数的方式一致。
        URIBuilder builder = new URIBuilder("http://localhost/params");
        builder.addParameter("name", "post");
        builder.addParameter("password", "postPassword");
        HttpResponse postResponse = client.execute(new HttpPost(builder.build()));
        System.out.println(EntityUtils.toString(postResponse.getEntity(), "UTF-8"));
    }

    public static void testPostParamswithBody() throws Exception{
        HttpClient client = HttpClients.createDefault();
        // 请求体传递参数
        HttpPost bodyParamsPost = new HttpPost("http://localhost/bodyParams");
        // 定义请求协议体,设置请求参数。 使用请求体传递参数的时候,需要定义请求体格式。默认是表单格式。
        // 使用URIBuilder构建的URI对象,就是请求体传递参数的。
        User u1 = new User();
        u1.setName("name1");
        u1.setPassword("password1");
        User u2 = new User();
        u2.setName("name2");
        u2.setPassword("password2");
        List<User> users = new ArrayList<User>();
        users.add(u1);
        users.add(u2);
        // 把集合users -> JSON字符串
        // 创建Jackson中的转换器对象
        ObjectMapper objectMapper = new ObjectMapper();
        // java对象转换成JSON格式字符串
        String paramsString = objectMapper.writeValueAsString(users);
        System.out.println(paramsString);
        // 拼接一个JSON格式字符串,表示请求参数, 一个List<User>
        // String paramsString = "[" + u1.toString() + ", " + u2.toString() + "]";
        HttpEntity entity = new StringEntity(paramsString, "application/json", "UTF-8");
        bodyParamsPost.setEntity(entity);

        String responseString = EntityUtils.toString(client.execute(bodyParamsPost).getEntity(), "UTF-8");

        String userString = responseString.substring(1, responseString.indexOf("},")+1);
        User responseUser = objectMapper.readValue(userString, User.class);
        System.out.println(responseUser);

        // 构建一个Jackson识别的Java类型映射。
        JavaType valueType = objectMapper.getTypeFactory().constructParametricType(List.class, User.class);
        List<User> responseList = objectMapper.readValue(responseString, valueType);
        System.out.println(responseList);
    }

4 启动TestHttpClient测试

结果如下:

相关推荐
我不会插花弄玉5 小时前
13.多路转接epoll【由浅入深-网络】
网络·c++·epoll
最强小杰5 小时前
某 OpenAI 兼容网关上的 `kimi-k3.1-pro`:Cline、Zed 接入与 SSE 排错示例
java·服务器·网络·ai
郝学胜-神的一滴7 小时前
Effective STL 条款03:容器中的对象复制要廉价且正确
开发语言·数据结构·c++·算法·rpc·stl
张小姐的猫9 小时前
【基于 WebSocket 的多用户网页五子棋】—— 整合封装服务器模块设计实现2️⃣
服务器·websocket·网络协议
上海潭龙东海科技有限公司11 小时前
智慧堆场动态模型三维实时孪生重构智能管控
大数据·网络·数据库·算法·重构
jianqiang.xue15 小时前
把Agent塞进MCU:工具次数和上下文长度怎么卡
java·前端·网络·单片机·esp32·ai编程
离凌寒17 小时前
一、关于qt编写的mqtt工具与tcp工具使用说明
网络·网络协议·tcp/ip
如夏倾城17 小时前
五大远程桌面协议:RDP、SSH、VNC/RFB、Citrix ICA/HDX 与 VMware Blast Extreme
运维·windows·网络协议·安全·自动化·ssh·远程工作
羽落•无痕(苏晗默)18 小时前
华为数通IA——14、网络服务与应用:TCP/UDP 传输层协议与 FTP、Telnet、SSH 实践
网络·网络协议·tcp/ip·网络安全·华为·udp·信息与通信
0xBADCODE18 小时前
2026 工业互联网安全大赛 · 全国预选赛题解系列密码学方向 crypto-5
网络·安全·web安全·网络安全·系统安全·密码学