【RPC】认识httpclient(一)

HttpClient

HttpClient的主要功能:

  • 实现了所有 HTTP 的方法(GET、POST、PUT、HEAD、DELETE、HEAD、OPTIONS 等)
  • 支持 HTTPS 协议
  • 支持代理服务器(Nginx等)等
  • 支持自动(跳转)转向

Demo结构

 Entity类

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User implements Serializable{
    private String name;
    private String password;
    private Date birth;
}

服务端

0、引入依赖

   <dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>2.6.4</version>
            <scope>import</scope>
            <type>pom</type>
        </dependency>
    </dependencies>
   </dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.jane</groupId>
            <artifactId>httpclient_entity</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
    </dependencies>

1、Controller

@Controller
public class TestController {
    //无参
    @RequestMapping(value = "/test",produces = {"application/json;charset-set:utf-8"})
    @ResponseBody
    public String test(){
        return "{\"msg\":\"testtesttest\"}";
    }

    //有参 get形式
    @RequestMapping(value = "/params",produces = {"application/json;charset-set:utf-8"})
    @ResponseBody
    public String test2(String name,String password){
        System.out.println("name:"+name+";password:"+password);
        return  "{\"msg\":\"登录成功\",\"user\":{\"name\":\""+name+"\",\"password\":\""+password+"\"}}";
    }

    //有参 post形式
    @RequestMapping(value = "/bodyparams",produces = {"application/json;charset-set:utf-8"})
    @ResponseBody
    @CrossOrigin
    public String test3(@RequestBody List<User> users){
        System.out.println(users);
        return users.toString();
    }
}

客户端

0、引入依赖

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>2.6.4</version>
                <scope>import</scope>
                <type>pom</type>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--        httpclient-->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.12</version>
        </dependency>
        <dependency>
            <groupId>com.jane</groupId>
            <artifactId>httpclient_entity</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.76</version>
        </dependency>
    </dependencies>

1、httpclient模拟无参的GET接口请求

    /**
     * 使用浏览器
     * 1.打开浏览器
     * 2.输入网址
     * 3.访问
     * 4.结果
     * 使用httpclient
     * 1.创建客户端=打开浏览器
     * 2.创建请求结果=输入地址
     * 3.发起请求=回车
     * 4.返回结果=页面结果
     */
    public static void testGetNoParam() throws IOException {
        //创建客户端
        CloseableHttpClient client = HttpClients.createDefault();
        //创建请求地址
        HttpGet urlGet = new HttpGet("http://localhost:80/test");
        //发起请求-返回结果
        CloseableHttpResponse response = client.execute(urlGet);
        //获取响应体,。响应体和响应头都是HTTP协议封装的对象,直接使用会有乱码。
        HttpEntity entity = response.getEntity();
        //转译
        String respString = EntityUtils.toString(entity,"utf-8");
        System.out.println("服务器响应数据为:"+respString);
        //关闭客户端=关闭浏览器
        client.close();
    }

2、httpclient模拟有参GET接口请求

    public static void testGetParam() throws URISyntaxException, IOException {
        CloseableHttpClient client = HttpClients.createDefault();
        //基于builder构建请求地址
        URIBuilder uriBuilder = new URIBuilder("http://localhost:80/params");
        //单参数传递
//        uriBuilder.addParameter("name","jane")
//                .addParameter("password","123456");
//        URI uri = uriBuilder.build();
        //多参数传递
        List<NameValuePair> nvps=new ArrayList<>();
        nvps.add(new BasicNameValuePair("name","jane"));
        nvps.add(new BasicNameValuePair("password","123456"));
        uriBuilder.addParameters(nvps);
        URI uri = uriBuilder.build();
        CloseableHttpResponse response = client.execute(new HttpGet(uri));
        String respString = EntityUtils.toString(response.getEntity(), "utf-8");
        System.out.println("服务器响应数据为:"+respString);
        client.close();
    }

NameValuePair简单名称值对节点类型,在发请求时,用该LIST发送

3、httpclient模拟POST接口请求

public static void testPost() throws IOException, URISyntaxException {
        //无参 POST
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost("http://localhost:80/test");
        CloseableHttpResponse response = client.execute(httpPost);
        String str = EntityUtils.toString(response.getEntity(), "utf-8");
        System.out.println("无参数POST:"+str);

        //有参-问号append地址
        URIBuilder uriBuilder = new URIBuilder("http://localhost:80/params");
        uriBuilder.addParameter("name","jane")
        .addParameter("password","123456");
        URI uri = uriBuilder.build();
        CloseableHttpResponse rep = client.execute(new HttpPost(uri));
        String str2 = EntityUtils.toString(rep.getEntity(), "utf-8");
        System.out.println("有参数POST:"+str2);

        //有参-有请求体
        HttpPost httpBody = new HttpPost("http://localhost:80/bodyparams");
        //请求协议体。默认表单格式
        User user = new User();
        user.setName("jane");
        user.setPassword("12345");
        User user2 = new User();
        user2.setName("jane2");
        user2.setPassword("12345789");
        List<User> users = Arrays.asList(user, user2);
        String paramsStr = JSONObject.toJSONString(users);
        HttpEntity httpEntity = new StringEntity(paramsStr,"application/json","UTF-8");
        httpBody.setEntity(httpEntity);
        System.out.println(EntityUtils.toString(client.execute(httpBody).getEntity(),"utf-8"));
        client.close();
    }

4、流程总结

1、创建Httpclient

CloseableHttpClient client = HttpClients.createDefault();     

2、创建请求(有参数)

(1)方法1:URIBuilder uriBuilder = new URIBuilder("地址")addParameter方法

或者 list中放参数 List<NameValuePair> nvps=new ArrayList<>(); addParameter(list)

(2)方法2:HttpEntity httpEntity = new StringEntity(paramsStr,"application/json","UTF-8");

paramsStr为JSON格式的string

3、创建请求地址

HttpPost httpPost = new HttpPost("地址") 或 new HttpGet("地址") 或 httpost.setEntity(httpEntity)

4、客户端执行并获取结果

client.execute(httpBody).getEntity(),"utf-8")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值