欢迎来到徐庆高(Tea)的个人博客网站
磨难很爱我,一度将我连根拔起。从惊慌失措到心力交瘁,我孤身一人,但并不孤独无依。依赖那些依赖我的人,信任那些信任我的人,帮助那些给予我帮助的人。如果我愿意,可以分裂成无数面镜子,让他们看见我,就像看见自己。察言观色和模仿学习是我的领域。像每个深受创伤的人那样,最终,我学会了随遇而安。
当前位置: 日志文章 > 详细内容

SpringBoot下使用RestTemplate实现远程服务调用的详细过程

2025年08月11日 Java
现如今的项目,由服务端向外发起网络请求的场景,基本上处处可见。resttemplate是一个执行http请求的同步阻塞式工具类,它仅仅只是在 http 客户端库(例如 jdk httpurlconne

现如今的项目,由服务端向外发起网络请求的场景,基本上处处可见。

resttemplate是一个执行http请求的同步阻塞式工具类,它仅仅只是在 http 客户端库(例如 jdk httpurlconnection,apache httpcomponents,okhttp 等)基础上,封装了更加简单易用的模板方法 api,方便程序员利用已提供的模板方法发起网络请求和处理,能很大程度上提升我们的开发效率

1、前置配置

在spring环境下使用resttemplate

如果当前项目是springboot,添加springboot启动依赖:

<dependency>
    <groupid>org.springframework.boot</groupid>
    <artifactid>spring-boot-starter-web</artifactid>
</dependency>

同时,将resttemplate配置初始化为一个bean对象

@configuration
public class resttemplateconfig {
    @bean
    public resttemplate resttemplate(){
        return new resttemplate();
    }
}

注意:在这种初始化方法,是使用了jdk自带的httpurlconnection作为底层http客户端实现。

在需要使用resttemplate的位置,注入并使用即可!

@autowired
private resttemplate resttemplate;

2、api实战:

resttemplate最大的特色就是对各种网络请求方式做了包装,能极大的简化开发人员的工作量,下面我们以get、post、put、delete为例,分别介绍各个api的使用方式

2.1 get请求:

2.1.1 不带参的get请求

@restcontroller
public class testcontroller {
    /**
     * 不带参的get请求
     * @return
     */
    @requestmapping(value = "testget", method = requestmethod.get)
    public user testget(){
        user user = new user();
        user.setcode("200");
        user.setmsg("请求成功,方法:testget");
        return user;
    }
}
@data
public class user {
    private string code;
    private string msg;
}
@autowired
private resttemplate resttemplate;
/**
 * 单元测试(不带参的get请求)
 */
@test
public void testget(){
    //请求地址
    string url = "http://localhost:8080/testget";
    //发起请求,直接返回对象
    user user = resttemplate.getforobject(url, user.class);
}

2.1.2 带参的get请求(使用占位符号传参)

@restcontroller
public class testcontroller {
    /**
     * 带参的get请求(restful风格)
     * @return
     */
    @requestmapping(value = "testgetbyrestful/{id}/{name}", method = requestmethod.get)
    public user testgetbyrestful(@pathvariable(value = "id") string id, @pathvariable(value = "name") string name){
        user user = new user();
        user.setcode("200");
        user.setmsg("请求成功,方法:testgetbyrestful,请求参数id:" +  id + "请求参数name:" + name);
        return user;
    }
}
@autowired
private resttemplate resttemplate;
 /**
 * 单元测试(带参的get请求)
 */
@test
public void testgetbyrestful(){
    //请求地址
    string url = "http://localhost:8080/testgetbyrestful/{1}/{2}";

    //发起请求,直接返回对象(restful风格)
    user user = resttemplate.getforobject(url, user.class, "001", "张三");
}

2.1.3 带参的get请求(restful风格)

@restcontroller
public class testcontroller {
    /**
     * 带参的get请求(restful风格)
     * @return
     */
    @requestmapping(value = "testgetbyparam", method = requestmethod.get)
    public user testgetbyparam(@requestparam("username") string username,
                                             @requestparam("userpwd") string userpwd){
        user user = new user();
        user.setcode("200");
        user.setmsg("请求成功,方法:testgetbyparam,请求参数username:" +  username + ",userpwd:" + userpwd);
        return user;
    }
}
@autowired
private resttemplate resttemplate;
 /**
 * 单元测试(带参的get请求)
 */
@test
public void testgetbyparam(){
    //请求地址
    string url = "http://localhost:8080/testgetbyparam?username={username}&userpwd={userpwd}";
    //请求参数
    map<string, string> urivariables = new hashmap<>();
    urivariables.put("username", "唐三藏");
    urivariables.put("userpwd", "123456");
    //发起请求,直接返回对象(带参数请求)
    user user = resttemplate.getforobject(url, user.class, urivariables);
}

2.1.4 getforentity使用示例

上面的所有的getforobject请求传参方法,getforentity都可以使用,使用方法上也几乎是一致的,只是在返回结果接收的时候略有差别。

使用responseentity<t> responseentity来接收响应结果。用responseentity.getbody()获取响应体。

/**
 * 单元测试
 */
@test
public void testallget(){
    //请求地址
    string url = "http://localhost:8080/testget";
    //发起请求,返回全部信息
    responseentity<user> response = resttemplate.getforentity(url, user.class);
    // 获取响应体
    system.out.println("http 响应body:" + response.getbody().tostring());
    // 以下是getforentity比getforobject多出来的内容
    httpstatus statuscode = response.getstatuscode();
    int statuscodevalue = response.getstatuscodevalue();
    httpheaders headers = response.getheaders();
    system.out.println("http 响应状态:" + statuscode);
    system.out.println("http 响应状态码:" + statuscodevalue);
    system.out.println("http headers信息:" + headers);
}

header设置参数

//请求头
httpheaders headers = new httpheaders();
headers.add("token", "123456789");
//封装请求头
httpentity<multivaluemap<string, object>> formentity = new httpentity<>(headers);
responseentity<string> response = resttemplate.exchange('请求的url', httpmethod.get, formentity, string.class);

2.2 get请求:

其实post请求方法和get请求方法上大同小异,resttemplatepost请求也包含两个主要方法:

  • postforobject():返回body对象
  • postforentity():返回全部的信息

2.2.1 模拟表单请求

模拟表单请求,post方法测试

@restcontroller
public class testcontroller {
    /**
     * 模拟表单请求,post方法测试
     * @return
     */
    @requestmapping(value = "testpostbyform", method = requestmethod.post)
    public user testpostbyform(@requestparam("username") string username,
                                        @requestparam("userpwd") string userpwd){
        user user = new user();
        user.setcode("200");
        user.setmsg("请求成功,方法:testpostbyform,请求参数username:" + username + ",userpwd:" + userpwd);
        return user;
    }
}
@autowired
private resttemplate resttemplate;
/**
 * 模拟表单提交,post请求
 */
@test
public void testpostbyform(){
    //请求地址
    string url = "http://localhost:8080/testpostbyform";
    // 请求头设置,x-www-form-urlencoded格式的数据
    httpheaders headers = new httpheaders();
    headers.setcontenttype(mediatype.application_form_urlencoded);
    //提交参数设置
    multivaluemap<string, string> map = new linkedmultivaluemap<>();
    map.add("username", "唐三藏");
    map.add("userpwd", "123456");
    // 组装请求体
    httpentity<multivaluemap<string, string>> request = new httpentity<>(map, headers);
    //发起请求
    user user = resttemplate.postforobject(url, request, user.class);
}

2.2.2 模拟表单请求,post方法测试(接收对象)

@restcontroller
public class testcontroller {
    /**
     * 模拟表单请求,post方法测试
     * @param request
     * @return
     */
    @requestmapping(value = "testpostbyformandobj", method = requestmethod.post)
    public user testpostbyform(uservo request){
        user user = new user();
        user.setcode("200");
        user.setmsg("请求成功,方法:testpostbyformandobj,请求参数:" + json.tojsonstring(request));
        return user;
    }
}
@data
public class uservo {
   private string username;
   private string userpwd;
}
@autowired
private resttemplate resttemplate;
/**
 * 模拟表单提交,post请求
 */
@test
public void testpostbyform(){
    //请求地址
    string url = "http://localhost:8080/testpostbyformandobj";
    // 请求头设置,x-www-form-urlencoded格式的数据
    httpheaders headers = new httpheaders();
    headers.setcontenttype(mediatype.application_form_urlencoded);
    //提交参数设置
    multivaluemap<string, string> map = new linkedmultivaluemap<>();
    map.add("username", "唐三藏");
    map.add("userpwd", "123456");
    // 组装请求体
    httpentity<multivaluemap<string, string>> request = new httpentity<>(map, headers);
    //发起请求
    user user = resttemplate.postforobject(url, request, user.class);
}

2.2.3 模拟json请求,post方法测试

@restcontroller
public class testcontroller {
    /**
     * 模拟json请求,post方法测试
     * @param request
     * @return
     */
    @requestmapping(value = "testpostbyjson", method = requestmethod.post)
    public user testpostbyjson(@requestbody uservo request){
        user user = new user();
        user.setcode("200");
        user.setmsg("请求成功,方法:testpostbyjson,请求参数:" + json.tojsonstring(request));
        return user;
    }
}
@autowired
private resttemplate resttemplate;
/**
 * 模拟json提交,post请求
 */
@test
public void testpostbyjson(){
    //请求地址
    string url = "http://localhost:8080/testpostbyjson";
    //入参
    uservo vo = new uservo();
    vo.setusername("唐三藏");
    vo.setuserpwd("123456789");

    //发送post请求,并打印结果,以string类型接收响应结果json字符串
    responsebean responsebean = resttemplate.postforobject(url, vo, user.class);
}

2.3 put请求

put请求方法,可能很多人都没用过,它指的是修改一个已经存在的资源或者插入资源,该方法会向url代表的资源发送一个http put方法请求,示例如下

@restcontroller
public class testcontroller {
    /**
     * 模拟json请求,put方法测试
     * @param request
     * @return
     */
    @requestmapping(value = "testputbyjson", method = requestmethod.put)
    public void testputbyjson(@requestbody uservo request){
        system.out.println("请求成功,方法:testputbyjson,请求参数:" + json.tojsonstring(request));
    }
}
@autowired
private resttemplate resttemplate;
/**
 * 模拟json提交,put请求
 */
@test
public void testputbyjson(){
    //请求地址
    string url = "http://localhost:8080/testputbyjson";
    //入参
    uservo request = new uservo();
    request.setusername("唐三藏");
    request.setuserpwd("123456789");

    //模拟json提交,put请求
    resttemplate.put(url, request);
}

2.4 delete请求

与之对应的还有delete方法协议,表示删除一个已经存在的资源,该方法会向url代表的资源发送一个http delete方法请求。

@restcontroller
public class testcontroller {
    /**
     * 模拟json请求,delete方法测试
     * @return
     */
    @requestmapping(value = "testdeletebyjson", method = requestmethod.delete)
    public void testdeletebyjson(){
        system.out.println("请求成功,方法:testdeletebyjson");
    }
}
@autowired
private resttemplate resttemplate;
/**
 * 模拟json提交,delete请求
 */
@test
public void testdeletebyjson(){
    //请求地址
    string url = "http://localhost:8080/testdeletebyjson";

    //模拟json提交,delete请求
    resttemplate.delete(url);
}

2.5 exchange方法

如果以上方法还不满足你的要求。在resttemplate工具类里面,还有一个exchange通用协议请求方法,它可以发送get、post、delete、put、options、patch等等http方法请求。

到此这篇关于springboot下使用resttemplate实现远程服务调用的详细过程的文章就介绍到这了,更多相关springboot resttemplate远程服务调用内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!