优秀的编程知识分享平台

网站首页 > 技术文章 正文

Spring RestTemplate 远程调用(spring配置resttemplate)

nanyue 2024-09-08 06:07:27 技术文章 8 ℃

哈喽大家好,昨晚给大家介绍了SpringCloud远程服务调用的方式RPC和HTTP,今天接着给大家介绍基于http通讯协议Spring RestTemplate 的远程调用。

课程目标

了解Spring RestTemplate的应用

原理

http工具类包一般情况下有如下三种,它们都可以方便的进行http服务调用:

  • HttpClient
  • okHttp
  • JDK原生URLConnection

HttpClient、okHttp都是URLConnection的分支,Spring 提供的RestTemplate工具类底层就是对上述的okHttp、JDK原生URLConnection工具类进行了封装,可在spring项目中使用RestTemplate进行服务调用,而后面我们将要讲到的Fegin 则是对JDK原生URLConnection进行了封装。

实操步骤概览

1:引入依赖包

2:定义测试类 RestTemplateDemo.java

3:运行测试结果

下面进入具体的coding环节

1:引入依赖包

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>


2:定义测试类 RestTemplateDemo.java


package com.helloworldgo.client;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.junit.Test;
import org.springframework.web.client.RestTemplate;
import com.helloworldgo.entiry.User;

public class RestTemplateDemo {

    @Test
    public void testHttpClient() throws  Exception{
        // 请求地址
        /*
            String url = "http://10.183.102.118:8082/auth/user/get/8";
            RestTemplate restTemplate = new RestTemplate();
            User user = restTemplate.getForObject(url, User.class);
            System.out.println(user);
        */
        //或者使用
        // 请求地址
        String url = "http://10.183.102.118:8082/auth/user/get/8";
        //使用resttemplate来调用地址获取数据
        RestTemplate restTemplate = new RestTemplate();
        // 请求地址,转换的json数据放入ResponseEntity
        ResponseEntity<User> user = restTemplate.getForEntity(url, User.class);
        //获取用户信息
        System.out.println(user.getBody());
    }

}


3:测试结果如下

User(id=8, eName=chuanjianguo, password=iLoveChina, cName=川建国, age=74, sex=1)


关于HttpClient和okHttp如何选型,可参考下面的博文

HTTP连接客户端,选 HttpClient 还是 OkHttp?

最近发表
标签列表