温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java基于HttpClient如何实现RPC

发布时间:2021-10-18 09:11:52 来源:亿速云 阅读:145 作者:小新 栏目:开发技术

这篇文章给大家分享的是有关Java基于HttpClient如何实现RPC的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

    1 HttpClient简介

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

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

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

    2 代码实现

    2.1 服务端

    新建项目HttpClientServer

    2.1.1 新建控制器
    com.mrshun.controller.DemoController
    
    @Controller
    public class DemoController {
        @RequestMapping("/demo")
        @ResponseBody
        public String demo(String param){
            return "demo"+param;
        }
    }
    2.1.2 新建启动器

    新建启动器

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

    2.2 客户端

    新建HttpClientDemo项目

    2.2.1 添加依赖
    <dependencies>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.10</version>
        </dependency>
    </dependencies>
    2.2.2 新建类

    新建com.mrshun.HttpClientDemo,编写主方法。

    2.2.2.1 使用GET方法访问

    public static void main(String[] args) {
        try {
         //创建http工具(理解成:浏览器) 发起请求,解析响应
            CloseableHttpClient httpClient = HttpClients.createDefault();
            //请求路径
            URIBuilder uriBuilder = new URIBuilder("http://localhost:8080/demo");
            uriBuilder.addParameter("param", "get123");
            //创建HttpGet请求对象
            HttpGet get = new HttpGet(uriBuilder.build());
            //创建响应对象
            CloseableHttpResponse response = httpClient.execute(get);
            //由于响应体是字符串,因此把HttpEntity类型转换为字符串类型,并设置字符编码
            String result = EntityUtils.toString(response.getEntity(), "utf-8");
            //输出结果
            System.out.println(result);
            //释放资源
            response.close();
            httpClient.close();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    2.2.2.2 使用POST方式访问

    public class HttpClientDemo {
        public static void main(String[] args) {
            try {
             //创建http工具(理解成:浏览器) 发起请求,解析响应
                CloseableHttpClient httpClient = HttpClients.createDefault();
                //创建HttpPOST请求对象
                HttpPost post = new HttpPost("http://localhost:8080/demo");
                //所有请求参数
                List<NameValuePair> params = new ArrayList<>();
                params.add(new BasicNameValuePair("param","123"));
                //创建HttpEntity接口的文本实现类的对象,放入参数并设置编码
                HttpEntity httpEntity = new UrlEncodedFormEntity(params,"utf-8");
                //放入到HttpPost对象中
                post.setEntity(httpEntity);            
                //创建响应对象
                CloseableHttpResponse response = httpClient.execute(post);
                //由于响应体是字符串,因此把HttpEntity类型转换为字符串类型
                String result = EntityUtils.toString(response.getEntity());
                //输出结果
                System.out.println(result);
                //释放资源
                response.close();
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    3. Jackson用法

    3.1 把对象转换为json字符串

    ObjectMapper objectMapper = new ObjectMapper();
    People peo = new People();
    objectMapper.writeValueAsString(peo);

    3.2 把json字符串转换为对象

    ObjectMapper objectMapper = new ObjectMapper();
    People peo = objectMapper.readValue(content, People.class);

    3.3 把json字符串转换为List集合

    ObjectMapper objectMapper = new ObjectMapper();
    JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, People.class);
    List<People> list = objectMapper.readValue(content, javaType);

    4 HttpClient请求包含JSON

    4.1 java代码实现

    public class HttpClientDemo {
        public static void main(String[] args) {
            try {
                CloseableHttpClient httpClient = HttpClients.createDefault();
                HttpPost post = new HttpPost("http://localhost:8080/demo");
                HttpEntity httpEntity= null;
    String json = "{}";
                StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
                post.setEntity(entity);
                CloseableHttpResponse response = httpClient.execute(post);
                String result = EntityUtils.toString(response.getEntity());
                System.out.println(result);
                response.close();
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    5 控制器接口参数

    @RequestBody把请求体中流数据转换为指定的对象。多用在请求参数是json数据且请求的Content-Type=”application/json”

    @RequestMapping("/demo4")
    @ResponseBody
    public String demo4(@RequestBody List<People> list) {
        System.out.println(list);
        return list.toString();
    }

    6 Ajax发送json参数写法

    var json = '[{"id":123,"name":"mrshun"},{"id":123,"name":"zhangyongshun"}]';
     $.ajax({
         url:'/demo5',
         type:'post',
         success:function(data){
             alert(data);
             for(var i = 0 ;i<data.length;i++){
    
                 alert(data[i].id +"  "+data[i].name);
             }
         },
         contentType:'application/json',//请求体中内容类型
         dataType:'json',//响应内容类型。
         data:json
     });

    7 跨域

    • 跨域:协议、ip、端口中只要有一个不同就是跨域请求。

    • 同源策略:浏览器默认只允许ajax访问同源(协议、ip、端口都相同)内容。

    解决同源策略:

    在控制器接口上添加@CrossOrigin。表示允许跨域。本质在响应头中添加Access-Control-Allow-Origin: *

    var json = '[{"id":123,"name":"mrshun"},{"id":456,"name":"zhangyongshun"}]';
     $.ajax({
         url:'/demo5',
         type:'post',
         success:function(data){
             alert(data);
             for(var i = 0 ;i<data.length;i++){
    
                 alert(data[i].id +"  "+data[i].name);
             }
         },
         contentType:'application/json',//请求体中内容类型
         dataType:'json',//响应内容类型。
         data:json
     });

    感谢各位的阅读!关于“Java基于HttpClient如何实现RPC”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

    向AI问一下细节

    免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

    AI