龙空技术网

「微服务~远程调用」HttpClient入门 保姆级教学

Java架构师鸨哥 222

前言:

目前我们对“webservice调用css”都比较关怀,你们都需要剖析一些“webservice调用css”的相关知识。那么小编同时在网摘上收集了一些有关“webservice调用css””的相关内容,希望看官们能喜欢,同学们一起来学习一下吧!

本期介绍

本期主要介绍微服务~远程调用

文章目录

什么是远程调用

基本功能

GET请求--无参:查询所有

练习:GET请求:查询详情

GET请求--有参:拼凑URL

POST请求:手动拼凑JSON

概述前言

2个团队,分别开发了“商品管理系统”和“用户管理系统”

问题:“商品管理系统”需要使用“用户管理系统”某个功能,怎么办?

根据用户的会员等级,显示不同的打折

什么是远程调用客户端程序通过接口调用服务端程序,并获得该服务返回的数据的过程,称为远程调用。“商品管理系统”调用“用户管理系统”的过程,就是“远程调用”。此时“商品管理系统”相当于模拟“浏览器”。调用方式常见的远程调用方式有2种:RPC:Remote Produce Call远程过程调用,==自定义数据==格式的远程调用方式。基于原生TCP通信,速度快,效率高。Http:采用http协议远程调用方式,==规定==了数据传输的格式,缺点是消息封装臃肿。现在热门的Rest风格,就可以通过http协议来实现。常见框架 :RPC常见框架: dubbo、WebServiceHttp常见框架: HttpClient、RestTemplate

区别

HTTP

RPC

速度

较慢

难度

简单

复杂

灵活性

灵活,跨平台、跨语言

如何选择

那么我们该怎么选择呢?==微服务==,基于Spring Cloud的微服务,更加强调的是独立、自治、灵活,一般都会采用 基于Http 的Rest风格服务。搭建环境父项目项目名:nacos-parent-2.1添加坐标:

<parent>        <groupId>org.springframework.cloud</groupId>        <artifactId>spring-cloud-build</artifactId>        <version>2.3.5.RELEASE</version>    </parent>    <properties>        <spring.cloud.version>Hoxton.SR12</spring.cloud.version>        <spring.cloud.alibaba.version>2.2.7-SNAPSHOT</spring.cloud.alibaba.version>        <mybatis.plus.starter.version>3.4.0</mybatis.plus.starter.version>        <durid.starter.version>1.1.10</durid.starter.version>        <swagger.version>2.7.0</swagger.version>        <jwt.jjwt.version>0.9.0</jwt.jjwt.version>        <jwt.joda.version>2.9.7</jwt.joda.version>    </properties>    <dependencyManagement>        <dependencies>            <!-- Spring Dependencies -->            <dependency>                <groupId>org.springframework.boot</groupId>                <artifactId>spring-boot-dependencies</artifactId>                <version>${spring-boot.version}</version>                <type>pom</type>                <scope>import</scope>            </dependency>            <dependency>                <groupId>org.springframework.cloud</groupId>                <artifactId>spring-cloud-dependencies</artifactId>                <version>${spring.cloud.version}</version>                <type>pom</type>                <scope>import</scope>            </dependency>            <dependency>                <groupId>com.alibaba.cloud</groupId>                <artifactId>spring-cloud-alibaba-dependencies</artifactId>                <version>${spring.cloud.alibaba.version}</version>                <type>pom</type>                <scope>import</scope>            </dependency>            <!-- mybatis-plus -->            <dependency>                <groupId>com.baomidou</groupId>                <artifactId>mybatis-plus-boot-starter</artifactId>                <version>${mybatis.plus.starter.version}</version>            </dependency>            <!-- Druid连接池 -->            <dependency>                <groupId>com.alibaba</groupId>                <artifactId>druid-spring-boot-starter</artifactId>                <version>${durid.starter.version}</version>            </dependency>            <!--swagger2-->            <dependency>                <groupId>io.springfox</groupId>                <artifactId>springfox-swagger2</artifactId>                <version>${swagger.version}</version>            </dependency>            <dependency>                <groupId>io.springfox</groupId>                <artifactId>springfox-swagger-ui</artifactId>                <version>${swagger.version}</version>            </dependency>        </dependencies>    </dependencyManagement>
测试数据项目环境项目:nacos-data添加依赖
<dependencies>        <!--web起步依赖-->        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-web</artifactId>        </dependency>        <!--swagger2-->        <dependency>            <groupId>io.springfox</groupId>            <artifactId>springfox-swagger2</artifactId>        </dependency>        <dependency>            <groupId>io.springfox</groupId>            <artifactId>springfox-swagger-ui</artifactId>        </dependency>        <!--支持lombok-->        <dependency>            <groupId>org.projectlombok</groupId>            <artifactId>lombok</artifactId>        </dependency>    </dependencies>
yml配置
server:  port: 7778
拷贝BaseResult 和 Swagger2ConfigurationV3编写启动类
package com.czxy;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;/** * Created by liangtong. */@SpringBootApplicationpublic class DataApplication {    public static void main(String[] args) {        SpringApplication.run(DataApplication.class, args);    }}
基本功能创建JavaBean
package com.czxy.domain;import lombok.AllArgsConstructor;import lombok.Data;import lombok.NoArgsConstructor;/** * Created by liangtong. */@Data@NoArgsConstructor@AllArgsConstructorpublic class User {    private Integer uid;    private String username;    private String password;    private Integer age;}
编写基本功能(模拟数据)
package com.czxy.controller;import com.czxy.domain.User;import com.czxy.vo.BaseResult;import org.springframework.web.bind.annotation.*;import java.util.ArrayList;import java.util.List;/** * Created by liangtong. */@RestController@RequestMapping("/user")public class UserController {    @GetMapping    public BaseResult findAll(){        List<User> list = new ArrayList<>();        list.add(new User(1,"jack","1234",18));        list.add(new User(2,"rose","5678",21));        list.add(new User(3,"tom","6666",25));        return BaseResult.ok("查询所有",list);    }    @GetMapping("/{uid}")    public BaseResult findById(@PathVariable("uid")Integer uid){        User user = new User(1,"jack","1234",18);        return BaseResult.ok("查询成功",user);    }    @GetMapping("/search")    public BaseResult search(User user){        System.out.println(user);        return BaseResult.ok("查询成功",user);    }    @PostMapping    public BaseResult save(@RequestBody User user){        System.out.println(user);//        return ResponseEntity.status(302).body(BaseResult.ok("添加成功"));        return BaseResult.ok("添加成功");    }    @PutMapping    public BaseResult update(@RequestBody User user){        System.out.println(user);        return BaseResult.ok("更新成功");    }    @DeleteMapping("/{uid}")    public BaseResult deleteById(@PathVariable("uid")Integer uid){        System.out.println(uid);        return BaseResult.ok("删除成功");    }}
测试

HttpClient入门概述HttpClient 是Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。搭建环境创建项目:nacos-httppom配置

<dependencies>        <!--web起步依赖-->        <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.6</version>        </dependency>        <!--支持lombok-->        <dependency>            <groupId>org.projectlombok</groupId>            <artifactId>lombok</artifactId>        </dependency>        <!--fastjson-->        <dependency>            <groupId>com.alibaba</groupId>            <artifactId>fastjson</artifactId>            <version>1.2.49</version>        </dependency>        <!-- 测试 -->        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-test</artifactId>        </dependency>    </dependencies>
创建启动类
package com.czxy;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class HttpApplication {    public static void main(String[] args) {        SpringApplication.run(HttpApplication.class, args);    }}
编写测试类
package com.czxy;public class TestHttp {}
基本功能GET请求--无参:查询所有以get请求的方式,获得所有结果1.创建客户端 (相当于打开浏览器)。CloseableHttpClient2.创建GET请求实例(确定访问路径) HTTPGet3.发送请求(回车访问)execute4.判断响应的状态码2005.通过工具处理响应内容6.关闭资源代码
@Test    public void testFindAll() {        try {            //1 创建Httpclient对象,相当于打开了浏览器            CloseableHttpClient httpClient = HttpClients.createDefault();            //2 确定请求方式和请求路径,相当于在浏览器输入地址            HttpGet httpGet = new HttpGet(";);            //3 执行请求并获取响应,相当于敲完地址后按下回车。            CloseableHttpResponse response = httpClient.execute(httpGet);            if(response.getStatusLine().getStatusCode() == 200) {                String str = EntityUtils.toString(response.getEntity());                System.out.println(str);            }            response.close();            httpClient.close();        } catch (IOException e) {            e.printStackTrace();        }    }
如果响应的数据乱码,需要手动设定练习:GET请求:查询详情
@Test    public void testFindId() {        String id = "1";        try {            //1 创建Httpclient对象,相当于打开了浏览器            CloseableHttpClient httpClient = HttpClients.createDefault();            //2 确定请求方式和请求路径,相当于在浏览器输入地址            HttpGet httpGet = new HttpGet("; + id);            //3 执行请求并获取响应,相当于敲完地址后按下回车。            CloseableHttpResponse response = httpClient.execute(httpGet);            if(response.getStatusLine().getStatusCode() == 200) {                String str = EntityUtils.toString(response.getEntity(),"UTF-8");                System.out.println(str);            }            response.close();            httpClient.close();        } catch (IOException e) {            e.printStackTrace();        }    }
GET请求--有参:拼凑URL基本使用
@Test    public void testDemo03(){        try {            //1 创建Httpclient对象,相当于打开了浏览器            CloseableHttpClient httpClient = HttpClients.createDefault();            StringBuilder params = new StringBuilder();            params.append("username=张三");            params.append("&");            params.append("password=1234");            //2 确定请求方式和请求路径,相当于在浏览器输入地址            HttpGet httpGet = new HttpGet("; + "?" + params.toString());            //3 执行请求并获取响应,相当于敲完地址后按下回车。            CloseableHttpResponse response = httpClient.execute(httpGet);            if(response.getStatusLine().getStatusCode() == 200){                // 3.1 获得响应数据的类型                System.out.println(response.getEntity().getContentType());                // 3.2 获得响应体内容                String str = EntityUtils.toString(response.getEntity(),"UTF-8");                System.out.println(str);            }            response.close();            httpClient.close();        } catch (IOException e) {            e.printStackTrace();        }    }
拼凑特殊数据:URL中的特殊符号,需要使用URLEncoder处理
@Test    public void testDemo04(){        try {            //1 创建Httpclient对象,相当于打开了浏览器            CloseableHttpClient httpClient = HttpClients.createDefault();            StringBuilder params = new StringBuilder();            params.append("username=" + URLEncoder.encode("&","UTF-8"));            params.append("&");            params.append("password=1234");            //2 确定请求方式和请求路径,相当于在浏览器输入地址            HttpGet httpGet = new HttpGet("; + "?" + params.toString());            //3 执行请求并获取响应,相当于敲完地址后按下回车。            CloseableHttpResponse response = httpClient.execute(httpGet);            if(response.getStatusLine().getStatusCode() == 200){                // 3.1 获得响应数据的类型                System.out.println(response.getEntity().getContentType());                // 3.2 获得响应体内容                String str = EntityUtils.toString(response.getEntity(),"UTF-8");                System.out.println(str);            }            response.close();            httpClient.close();        } catch (IOException e) {            e.printStackTrace();        }    }
POST请求:手动拼凑JSON
@Test    public void testInsert() {        try {            //1 创建Httpclient对象,相当于打开了浏览器            CloseableHttpClient httpClient = HttpClients.createDefault();            //2 确定请求方式和请求路径,相当于在浏览器输入地址            HttpPost httpPost = new HttpPost (";);            // 2.1 准备json数据            String jsonStr = "{\n" +                    "      \"uid\": \"1\",\n" +                    "      \"username\": \"jack\",\n" +                    "      \"password\": \"1234\",\n" +                    "      \"age\": \"18\"\n" +                    "    }";            // 2.2 设置请求体            httpPost.setEntity(new StringEntity(jsonStr,"UTF-8"));            // 2.3 设置请求数据类型为json            httpPost.setHeader("content-type","application/json;charset=UTF-8");            //3 执行请求并获取响应,相当于敲完地址后按下回车。            CloseableHttpResponse response = httpClient.execute(httpPost);            if(response.getStatusLine().getStatusCode() == 200) {                String str = EntityUtils.toString(response.getEntity(),"UTF-8");                System.out.println(str);            }            response.close();            httpClient.close();        } catch (IOException e) {            e.printStackTrace();        }    }
POST请求:fastjsonfastjson 是阿里巴巴提供最快的json转换工具如果要使用fastjson,修改pom.xml文件,添加坐标(如果已有,忽略此步)
<!--fastjson--><dependency>    <groupId>com.alibaba</groupId>    <artifactId>fastjson</artifactId>    <version>1.2.49</version></dependency>
拷贝JavaBean:User代码
@Test    public void testInsert2() {        try {            //1 创建Httpclient对象,相当于打开了浏览器            CloseableHttpClient httpClient = HttpClients.createDefault();            //2 确定请求方式和请求路径,相当于在浏览器输入地址            HttpPost httpPost = new HttpPost (";);            // 2.1 准备json数据            User user = new User(1,"jack","1234",18);            String jsonStr = JSON.toJSONString(user);            // 2.2 设置请求体            httpPost.setEntity(new StringEntity(jsonStr,"UTF-8"));            // 2.3 设置请求数据类型为json            httpPost.setHeader("content-type","application/json;charset=UTF-8");            //3 执行请求并获取响应,相当于敲完地址后按下回车。            CloseableHttpResponse response = httpClient.execute(httpPost);            if(response.getStatusLine().getStatusCode() == 200) {                String str = EntityUtils.toString(response.getEntity(),"UTF-8");                System.out.println(str);            }            response.close();            httpClient.close();        } catch (IOException e) {            e.printStackTrace();        }    }

标签: #webservice调用css