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测试

结果如下:

相关推荐
小羊没烦恼!几秒前
关于分布式锁原理的一些学习与思考-redis分布式锁,zookeeper分布式锁
java·服务器·网络·学习·负载均衡
小Ti客栈8 分钟前
Netty 零拷贝原理与实战
运维·服务器·网络
国科安芯10 分钟前
商业光学遥感载荷焦平面供电链的低噪声稳压器研究综述——以国科安芯ASP7A84AS型3A低压差线性稳压器为器件级参照
大数据·网络·嵌入式硬件·平面·卫星·商业航天·抗辐射
静以修身zzz26 分钟前
计算云服务
运维·网络·云计算
星恒随风34 分钟前
Linux网络编程:应用层协议究竟是什么?从网络计算器到TCP Socket抽象基类完整实现
linux·网络·笔记·tcp/ip
万联WANFLOW1 小时前
异地组网速度忽快忽慢到底怎么回事?直连与中继的判断方法和处理步骤
运维·网络·网络协议·p2p
jimmyleeee1 小时前
Agent安全之六:(ASI06)记忆与上下文投毒——当 AI 把“昨天的错误”当成“今天的真理”
网络·人工智能·安全
辰辰观影1 小时前
字幕导入教程:外挂字幕一键加载方法
网络·经验分享
无糖可乐没有灵魂1 小时前
Golang ❀ Netdiag 一个Go开源的网络排障信息收集工具
网络
叼烟扛炮2 小时前
[LangChain] 学习笔记(02):LCEL 链式调用与动态模型配置实战
服务器·开发语言·网络·笔记·学习·langchain