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

结果如下:

相关推荐
帽儿山的枪手9 分钟前
程序员必掌握的iptables五表五链
linux·网络协议
Fortinet_CHINA10 分钟前
引领AI安全新时代 Accelerate 2025北亚巡展·北京站成功举办
网络·安全
dustcell.1 小时前
Cisco Packer Tracer 综合实验
网络
光芒Shine2 小时前
【物联网-ModBus-RTU
物联网·网络协议
量子-Alex3 小时前
【反无人机检测】C2FDrone:基于视觉Transformer网络的无人机间由粗到细检测
网络·transformer·无人机
Jeremy_Lee1234 小时前
grafana 批量视图备份及恢复(含数据源)
前端·网络·grafana
洛神灬殇4 小时前
【LLM大模型技术专题】「入门到精通系列教程」基于ai-openai-spring-boot-starter集成开发实战指南
网络·数据库·微服务·云原生·架构
上海云盾第一敬业销售4 小时前
高防IP可以防护什么攻击类型?企业网络安全的第一道防线
网络·tcp/ip·web安全
christine-rr5 小时前
征文投稿:如何写一份实用的技术文档?——以软件配置为例
运维·前端·网络·数据库·软件构建
happyh h h h p p p p6 小时前
部署DNS从服务器
运维·服务器·网络