RPC(3):HttpClient实现RPC之GET请求

1HttpClient简介

在JDK中java.net包下提供了用户HTTP访问的基本功能,但是它缺少灵活性或许多应用所需要的功能。

HttpClient起初是Apache Jakarta Common 的子项目。用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本。2007年成为顶级项目。

通俗解释:HttpClient可以实现使用Java代码完成标准HTTP请求及响应。

2 新建服务端项目

新建项目httpclient_rpc_server

2.1 修改maven配置文件

复制代码
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>2.3.2.RELEASE</version>
                <scope>import</scope>
                <type>pom</type>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

2.2 新建控制器

复制代码
package com.example.httpclientserver.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class TestController {

    /*
    * 带参数的get请求
    */
    @RequestMapping(value="/params", produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public String params(String name, String password){
        System.out.println("name - " + name + " ; password - " + password);
        return "{\"msg\":\"登录成功\", \"user\":{\"name\":\""+name+"\",\"password\":\""+password+"\"}}";
    }
    /*
     * 不带参数的get请求
     */
    @RequestMapping(value="/test",produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public String test(){
        return "{\"msg\":\"处理返回\"}";
    }
}

2.3 新建启动器

复制代码
package com.example.httpclientserver;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ServerApp {
    public static void main(String[] args) {
        SpringApplication.run(ServerApp.class, args);
    }
}

2.4 application.yml修改端口(非必需操作)

复制代码
server:
  port: 80

2.5 测试

3 新建客户端项目

新建客户端项目httpclient_rpc_client

3.1 添加maven依赖

复制代码
    <dependencies>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.12</version>
        </dependency>
    </dependencies>

3.2 新建主类进行httpclient访问

复制代码
package com.example.httpclient;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

public class TestHttpClient {
    public static void main(String[] args) throws Exception {
        //访问无参数GET请求
        testGetNoParams();
        //访问有参数GET请求
        testGetNoParams();
    }

    /**
     * 有参数GET请求
     * @throws IOException
     */
    public static void testGetParams() throws IOException, URISyntaxException {
        HttpClient client = HttpClients.createDefault();
        // 基于Builder构建请求地址
        URIBuilder builder = new URIBuilder("http://localhost:80/params");
        // 基于单参数传递,构建请求地址
//        builder.addParameter("name", "bjsxt");
//        builder.addParameter("password", "admin123");
//        URI uri = builder.build();

        // 基于多参数传递,构建请求地址
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("name","bjsxt"));
        nvps.add(new BasicNameValuePair("password", "admin123"));
        builder.addParameters(nvps);
        URI uri = builder.build();
        System.out.println(uri.toASCIIString());

        String result = EntityUtils.toString(client.execute(new HttpGet(uri)).getEntity());
        System.out.println(result);
    }

    /**
     * 无参数GET请求
     * 使用浏览器,访问网站的过程是:
     *  1、 打开浏览器
     *  2、 输入地址
     *  3、 访问
     *  4、 看结果
     * 使用HttpClient,访问WEB服务的过程:
     *  1、 创建客户端,相当于打开浏览器
     *  2、 创建请求地址, 相当于输入地址
     *  3、 发起请求, 相当于访问网站(回车键)
     *  4、 处理响应结果, 相当于浏览器显示结果
     */
    public static void testGetNoParams() throws IOException {
        // 创建客户端对象
        HttpClient client = HttpClients.createDefault();
        // 创建请求地址
        HttpGet get = new HttpGet("http://localhost:80/test");
        // 发起请求,接收响应对象
        HttpResponse response = client.execute(get);
        // 获取响应体。 响应数据是一个基于HTTP协议标准字符串封装的对象。
        // 所以,响应体和响应头,都是封装的HTTP协议数据。直接使用可能有乱码或解析错误
        HttpEntity entity = response.getEntity();

        // 通过HTTP实体工具类,转换响应体数据。 使用的字符集是UTF-8
        String responseString = EntityUtils.toString(entity, "UTF-8");

        System.out.println("服务器响应数据是 - [ " + responseString + " ]");

        // 回收资源
        client = null;

    }
}

其中有参请求方式有两种,一种是基于单参数传递,构建请求地址,如下:

复制代码
        // 基于单参数传递,构建请求地址
        builder.addParameter("name", "bjsxt");
        builder.addParameter("password", "admin123");
        URI uri = builder.build();

一种是基于多参数传递,构建请求地址,如下:

复制代码
        // 基于多参数传递,构建请求地址
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("name","bjsxt"));
        nvps.add(new BasicNameValuePair("password", "admin123"));
        builder.addParameters(nvps);
        URI uri = builder.build();

4 测试

启动httpclient_rpc_server和httpclient_rpc_client,httpclient_rpc_client控制台输出如下:

GET请求成功。

相关推荐
狐5723 分钟前
2025-06-02-IP 地址规划及案例分析
网络·网络协议·tcp/ip
黎茗Dawn1 小时前
5.子网划分及分片相关计算
网络·智能路由器
恰薯条的屑海鸥1 小时前
零基础在实践中学习网络安全-皮卡丘靶场(第十四期-XXE模块)
网络·学习·安全·web安全·渗透测试
科技小E1 小时前
口罩佩戴检测算法AI智能分析网关V4工厂/工业等多场景守护公共卫生安全
网络·人工智能
御承扬1 小时前
从零开始开发纯血鸿蒙应用之网络检测
网络·华为·harmonyos
DevSecOps选型指南10 小时前
2025软件供应链安全最佳实践︱证券DevSecOps下供应链与开源治理实践
网络·安全·web安全·开源·代码审计·软件供应链安全
利刃大大10 小时前
【在线五子棋对战】二、websocket && 服务器搭建
服务器·c++·websocket·网络协议·项目
国科安芯11 小时前
抗辐照MCU在卫星载荷电机控制器中的实践探索
网络·嵌入式硬件·硬件工程·智能硬件·空间计算
EasyDSS12 小时前
国标GB28181设备管理软件EasyGBS远程视频监控方案助力高效安全运营
网络·人工智能
玩转4G物联网12 小时前
零基础玩转物联网-串口转以太网模块如何快速实现与TCP服务器通信
服务器·网络·物联网·网络协议·tcp/ip·http·fs100p