SpringBoot之RestTemplate 简单常用使用示例

1.引入pom依赖

 <!--引入springboot父工程依赖-->
    <!--引入依赖作用:
    可以省去version标签来获得一些合理的默认配置
    -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.2.RELEASE</version>
    </parent>

    <!--因为用eureka,是springCloud的,所以引入springCloud版本锁定-->
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <!--spring cloud 版本-->
        <spring-cloud.version>Hoxton.SR10</spring-cloud.version>
    </properties>
    <!--引入Spring Cloud 依赖-->
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <!--引入提供Web开发场景依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--@LoadBalanced //需要用到此注解开启负载均衡的功能-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-commons</artifactId>
        </dependency>

        <!--@Data 减少JavaBean get...set...方法-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>


        <!--用于hutool工具类 对象转json字符串-->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-json</artifactId>
            <version>4.1.21</version>
        </dependency>

        <!--两个用来做测试的jar包-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>
    </dependencies>


2.配置启动类并 注入RestTemplate实体

  • @LoadBalanced : 负载均衡
                   通过服务名调用则可以使用个负载均衡(例如:http://MHH/test?age=12)
                   服务的 IP 和 Port,并把它拼接起来组合成的服务地址,没法实现客户端的负载均衡,会报错。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

/**
 * @创建人: Mhh
 * @创建时间: 2022/1/6
 * @描述:
 */
@SpringBootApplication
public class RestTemplateApplication {

    public static void main(String[] args) {
        SpringApplication.run(RestTemplateApplication.class);
    }

    @Bean
        //注入ioc
        //@LoadBalanced //开启负载均衡的功能(这里如果只是用ip地址访问的话就不存在负载均衡 会报错 除非是走的网关 用的Application name名)
    RestTemplate restTemplate() {
        return new RestTemplate();
    }
}


3. RestTemplate 简单常用使用示例


3.1 入参为空的请求方式

  • 没有入参

import com.it.mhh.restTemplate.entitiy.User;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.util.Map;
import java.util.Objects;

/**
 * @创建人: Mhh
 * @创建时间: 2022/1/6
 * @描述:
 */
@RestController
@RequestMapping("restTemplate")
public class RestTemplateController {

    
    @PostMapping("isEmpty")
    public String isEmpty() {
        return "已通过并返回:-->isEmpty()方法";
    }
}    


入参为空的请求方式测试结果:

  • exchange(RequestEntity<?> requestEntity, Class responseType)
                   responseType : 返回对象类型
                   RequestEntity(HttpMethod method, URI url):
                                        method:请求方式(POST/GET…)
                                         url : 请求路径 在这里插入图片描述
import cn.hutool.json.JSONUtil;
import com.it.mhh.restTemplate.entitiy.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

/**
 * @创建人: Mhh
 * @创建时间: 2022/1/6
 * @描述:
 */
@SpringBootTest
@RunWith(SpringRunner.class)
public class RestTemplateTest {


    @Autowired
    RestTemplate restTemplate;

    /*
     * @explain : 入参为空的请求方式
     *
     * @Author Mhh
     * @param null :
     * @return
     * @Date 2022/1/6 14:33
     */
    @Test
    public void isEmpty() throws URISyntaxException {
//        String url ="http://127.0.0.1:8080/restTemplate/isEmpty";
//
//        MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
        headers.add("请求头", "value值");
//        MultiValueMap<String, String> body = new LinkedMultiValueMap<String, String>();
        @RequestParam()请求的参数
        body.add("body键", "body值");
//        HttpEntity<MultiValueMap<String, String>> multiValueMapHttpEntity = new HttpEntity<MultiValueMap<String, String>>(body, headers);
//
//        //指定 restTemplate当遇到400或401响应时候也不要抛出异常,也要正常返回值
//        restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
//            @Override
//            public void handleError(ClientHttpResponse response) throws IOException {
//                //当响应的值为400或401时候也要正常响应,不要抛出异常
//                if (response.getRawStatusCode() != 400 && response.getRawStatusCode() != 401) {
//                    super.handleError(response);
//                }
//            }
//        });
//
                                                                   url:去寻找Eureka负载均衡查找地址
                                                                      HttpMethod.POST:请求方式
                                                                          multiValueMapHttpEntity:给对方的数据
                                                                              Map.class:以什么数据接收返回数据

//        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.POST, multiValueMapHttpEntity, String.class);
//        String s = exchange.getBody(); //返回的数据
//        System.out.println(s);
//---------------------------------------------------------------------------------------------------------

        String url = "http://127.0.0.1:8080/restTemplate/isEmpty";//需求地址
        ResponseEntity<String> exchange = restTemplate.exchange(new RequestEntity<String>(HttpMethod.POST, new URI(url)), String.class);
        String body = exchange.getBody();
        System.err.println(body);
    }
}


3.2 入参为@RequestParam() 请求方式

  • 入参在请求地址中

import com.it.mhh.restTemplate.entitiy.User;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.util.Map;
import java.util.Objects;

/**
 * @创建人: Mhh
 * @创建时间: 2022/1/6
 * @描述:
 */
@RestController
@RequestMapping("restTemplate")
public class RestTemplateController {

    
    @GetMapping("requestParam")
    public String requestParam(@RequestParam("id") String id, @RequestParam(value = "age", defaultValue = "1") Integer age) {
        return "已通过并返回:-->requestParam方法入参 id为: " + id + " age为: " + age;
    }
}    


入参为@RequestParam() 请求方式测试结果:

  • exchange(RequestEntity<?> requestEntity, Class responseType)
                   responseType : 返回对象类型
                   RequestEntity(HttpMethod method, URI url):
                                        method:请求方式(POST/GET…)
                                         url : 请求路径
    在这里插入图片描述
import cn.hutool.json.JSONUtil;
import com.it.mhh.restTemplate.entitiy.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

/**
 * @创建人: Mhh
 * @创建时间: 2022/1/6
 * @描述:
 */
@SpringBootTest
@RunWith(SpringRunner.class)
public class RestTemplateTest {


    @Autowired
    RestTemplate restTemplate;

    /**
     * @return void
     * @explain : 入参为requestParam 请求方式
     * @Author Mhh
     * @Date 2022/1/14 10:11
     */

    @Test
    public void requestParam() throws URISyntaxException {

//        /*只适合Post请求 GET请求会报400的错误*/
        String url = "http://127.0.0.1:8080/restTemplate/requestParam";

/*      //这个请求方式只适合Post请求方式
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<String, Object>();
        //@RequestParam()请求的参数
        body.add("id", "1234");
        body.add("age", 11);

        HttpEntity<MultiValueMap<String, Object>> multiValueMapHttpEntity = new HttpEntity<MultiValueMap<String, Object>>(body);
//指定 restTemplate当遇到400或401响应时候也不要抛出异常,也要正常返回值
        restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
            @Override
            public void handleError(ClientHttpResponse response) throws IOException {
                //当响应的值为400或401时候也要正常响应,不要抛出异常
                if (response.getRawStatusCode() != 400 && response.getRawStatusCode() != 401) {
                    super.handleError(response);
                }
            }
        });*/

//                                                                   url:去寻找Eureka负载均衡查找地址
//                                                                      HttpMethod.POST:请求方式
//                                                                          multiValueMapHttpEntity:给对方的数据
//                                                                              Map.class:以什么数据接收返回数据

        /*只适合Post请求 GET请求会报400的错误
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.POST, multiValueMapHttpEntity, String.class);
        */

        //
        ResponseEntity<String> exchange = restTemplate.exchange(new RequestEntity<String>(HttpMethod.GET, new URI(url + "?id=12344&age=13")), String.class);
        String s = exchange.getBody(); //返回的数据
        System.err.println(s); //已通过并返回:-->requestParam方法入参 id为: 12344 age为: 13
//---------------------------------------------------------------------------------------------------------
        /*只能Get请求*/
//        String url = "http://127.0.0.1:8080/restTemplate/requestParam";
//        ResponseEntity<String> forEntity = restTemplate.getForEntity(url + "?id=12344&age=13", String.class);
//        System.err.println(forEntity.getBody());
    }
}


3.3 入参为@RequestBody 请求方式

  • 入参在请求体中

import com.it.mhh.restTemplate.entitiy.User;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.util.Map;
import java.util.Objects;

/**
 * @创建人: Mhh
 * @创建时间: 2022/1/6
 * @描述:
 */
@RestController
@RequestMapping("restTemplate")
public class RestTemplateController {

    
    @PostMapping("requestBody")
    public Map<String, Object> requestBody(@RequestBody Map<String, Object> map) {
        return map;
    }

}    


入参为@RequestBody 请求方式测试结果:

  • exchange(String url, HttpMethod method, @Nullable HttpEntity<?> requestEntity, Class responseType, Object… uriVariables)
                   url: 请求路径
                   method:请求方式(POST/GET…)
                   requestEntity : 给对方传递的的数据
                   responseType :返回对象类型
                   uriVariables : 表示 url地址上传递的值(适用于restful风格)
    在这里插入图片描述
import cn.hutool.json.JSONUtil;
import com.it.mhh.restTemplate.entitiy.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

/**
 * @创建人: Mhh
 * @创建时间: 2022/1/6
 * @描述:
 */
@SpringBootTest
@RunWith(SpringRunner.class)
public class RestTemplateTest {


    @Autowired
    RestTemplate restTemplate;


    /**
     * @return void
     * @explain : 入参为@RequestBody请求
     * @Author Mhh
     * @Date 2022/1/14 10:44
     */
    @Test
    public void requestBody() {
        String url = "http://127.0.0.1:8080/restTemplate/requestBody";

        //配置请求头
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
//        headers.add("authorization", "Bearer 774720e6-8193-48b9-9fb0-7f0591ffbeef");
        headers.add("content-type", "application/json");

//MultiValueMap<String, Object> body = new LinkedMultiValueMap<String, Object>();
        Map<String, Object> body = new HashMap();
        body.put("page", 1);
        body.put("size", 5);
        body.put("mhh", "2");
        body.put("小白老师", 0);

        HttpEntity<String> multiValueMapHttpEntity = new HttpEntity<String>(JSONUtil.toJsonStr(body), headers);

//指定 restTemplate当遇到400或401响应时候也不要抛出异常,也要正常返回值
        restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
            @Override
            public void handleError(ClientHttpResponse response) throws IOException {
                //当响应的值为400或401时候也要正常响应,不要抛出异常
                if (response.getRawStatusCode() != 400 && response.getRawStatusCode() != 401) {
                    super.handleError(response);
                }
            }
        });
/*
                                                            //url:去寻找Eureka负载均衡查找地址
                                                                //HttpMethod.POST:请求方式
                                                                    //multiValueMapHttpEntity:给对方的数据
                                                                        //Map.class:以什么数据接收返回数据
*/
        ResponseEntity<Map> exchange = restTemplate.exchange(url, HttpMethod.POST, multiValueMapHttpEntity, Map.class);

        Map map = exchange.getBody(); //返回的数据
        System.err.println(map);

    }

}


3.4 入参为@RequestParam()与@RequestBody 请求方式

  • 入参在请求地址和请求体中

import com.it.mhh.restTemplate.entitiy.User;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.util.Map;
import java.util.Objects;

/**
 * @创建人: Mhh
 * @创建时间: 2022/1/6
 * @描述:
 */
@RestController
@RequestMapping("restTemplate")
public class RestTemplateController {

    
    @PostMapping("requestBodyAndRequestParam")
    public Map<String, Object> requestBody(@RequestParam("name") String name, @RequestBody Map<String, Object> map) {
        map.put("name", name);
        return map;
    }

}    


入参为@RequestParam()与@RequestBody 请求方式测试结果:

  • exchange(String url, HttpMethod method, @Nullable HttpEntity<?> requestEntity, Class responseType, Object… uriVariables)
                   url: 请求路径
                   method:请求方式(POST/GET…)
                   requestEntity : 给对方传递的的数据
                   responseType :返回对象类型
                   uriVariables : 表示 url地址上传递的值(适用于restful风格)
    在这里插入图片描述
import cn.hutool.json.JSONUtil;
import com.it.mhh.restTemplate.entitiy.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

/**
 * @创建人: Mhh
 * @创建时间: 2022/1/6
 * @描述:
 */
@SpringBootTest
@RunWith(SpringRunner.class)
public class RestTemplateTest {


    @Autowired
    RestTemplate restTemplate;


    /**
     * @return void
     * @explain : 入参同时有@RequestParam和@RequestBody
     * @Author Mhh
     * @Date 2022/1/14 11:09
     */

    @Test
    public void requestBodyAndRequestParam() {
        String url = "http://127.0.0.1:8080/restTemplate/requestBodyAndRequestParam";

        //配置请求头
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
//        headers.add("authorization", "Bearer 774720e6-8193-48b9-9fb0-7f0591ffbeef");
        headers.add("content-type", "application/json");

//MultiValueMap<String, Object> body = new LinkedMultiValueMap<String, Object>();
        Map<String, Object> body = new HashMap();
        body.put("小白老师", 0);

        HttpEntity<String> multiValueMapHttpEntity = new HttpEntity<String>(JSONUtil.toJsonStr(body), headers);

//指定 restTemplate当遇到400或401响应时候也不要抛出异常,也要正常返回值
        restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
            @Override
            public void handleError(ClientHttpResponse response) throws IOException {
                //当响应的值为400或401时候也要正常响应,不要抛出异常
                if (response.getRawStatusCode() != 400 && response.getRawStatusCode() != 401) {
                    super.handleError(response);
                }
            }
        });
/*
                                                            //url:去寻找Eureka负载均衡查找地址
                                                                //HttpMethod.POST:请求方式
                                                                    //multiValueMapHttpEntity:给对方的数据
                                                                        //Map.class:以什么数据接收返回数据
*/
        ResponseEntity<Map> exchange = restTemplate.exchange(url + "?name=mhh", HttpMethod.POST, multiValueMapHttpEntity, Map.class);

        Map map = exchange.getBody(); //返回的数据
        System.err.println(map);

    }



}


3.5 入参为@PathVariable 请求方式

  • restFul风格

import com.it.mhh.restTemplate.entitiy.User;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.util.Map;
import java.util.Objects;

/**
 * @创建人: Mhh
 * @创建时间: 2022/1/6
 * @描述:
 */
@RestController
@RequestMapping("restTemplate")
public class RestTemplateController {

    
    @PostMapping("{name}/restFul/{age}")
    public String restFul(@PathVariable("name")String name,@PathVariable("age")Integer age){
        return "已通过并返回:-->restFul方法入参 name为: " + name + " age为: " + age;
    }

}    


入参为@PathVariable 请求方式测试结果:

  • T postForObject(String url, @Nullable Object request, Class responseType, Object… uriVariables)
                   url: 请求路径
                   request: 给对方传递的的数据
                   responseType :返回对象类型
                   uriVariables : 表示 url地址上传递的值(适用于restful风格)
    在这里插入图片描述
import cn.hutool.json.JSONUtil;
import com.it.mhh.restTemplate.entitiy.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

/**
 * @创建人: Mhh
 * @创建时间: 2022/1/6
 * @描述:
 */
@SpringBootTest
@RunWith(SpringRunner.class)
public class RestTemplateTest {


    @Autowired
    RestTemplate restTemplate;



    /**
     * @return void
     * @explain : 入参为 @PathVariable
     * @Author Mhh
     * @Date 2022/1/17 16:36
     */
    @Test
    public void restFul() {
        String url = "http://127.0.0.1:8080/restTemplate/{name}/restFul/{age}";

        //配置请求体
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<String, Object>();

        HttpEntity<MultiValueMap<String, Object>> multiValueMapHttpEntity = new HttpEntity<MultiValueMap<String, Object>>(body);
        /*
        *
        *                                   //url:请求地址
        *                                       //request: 传递的参数
        *                                           //responseType: 返回对象实体
        *                                               //uriVariables: 请求地址上的值
        * */
        String s = restTemplate.postForObject(url, multiValueMapHttpEntity, String.class, "mhh", "12");
        System.err.println(s);
    }



}


3.6 入参为MultipartFile 附件 请求方式

  • 入参为附件 请求头headers 必须设置 “content-type=multipart/form-data”

import com.it.mhh.restTemplate.entitiy.User;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.util.Map;
import java.util.Objects;

/**
 * @创建人: Mhh
 * @创建时间: 2022/1/6
 * @描述:
 */
@RestController
@RequestMapping("restTemplate")
public class RestTemplateController {

    
    @PostMapping(value = "multipartFile", headers = "content-type=multipart/form-data")
    public void multipartFile(@RequestParam("multipartFile") MultipartFile multipartFile) {

        try {
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(Objects.requireNonNull(multipartFile.getOriginalFilename())));
            InputStream inputStream = multipartFile.getInputStream();
            int len;
            byte[] bytes = new byte[1024];
            while ((len = inputStream.read(bytes)) != -1) {
                bufferedOutputStream.write(bytes, 0, len);
                bufferedOutputStream.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}    


application.yml配置

  • 附件过大传不过去可配置上传大小(默认1MB)
spring:
  servlet:
    multipart:
      max-file-size: 10MB #设置单个文件的大小
      max-request-size: 10MB #设置单次请求的文件的总大小


入参为MultipartFile 附件 请求方式测试结果:

  • ResponseEntity exchange(String url, HttpMethod method, @Nullable HttpEntity<?> requestEntity, Class responseType, Object… uriVariables)
                   url: 请求路径
                   method: 请求方式(POST/GET…)
                   requestEntity: 给对方传递的的数据
                   responseType:返回对象类型
                   uriVariables: 表示 url地址上传递的值(适用于restful风格)
    在这里插入图片描述
import cn.hutool.json.JSONUtil;
import com.it.mhh.restTemplate.entitiy.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

/**
 * @创建人: Mhh
 * @创建时间: 2022/1/6
 * @描述:
 */
@SpringBootTest
@RunWith(SpringRunner.class)
public class RestTemplateTest {


    @Autowired
    RestTemplate restTemplate;



    /**
     * @return void
     * @explain : 入参为multipart 附件
     * @Author Mhh
     * @Date 2022/1/14 15:14
     */

    @Test
    public void multipartFile() {
        String url = "http://127.0.0.1:8080/restTemplate/multipartFile";
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();

//        headers.add("authorization", "Bearer 774720e6-8193-48b9-9fb0-7f0591ffbeef");
//        headers.add("content-type", "application/json");
        FileSystemResource resource = new FileSystemResource(new File("D:\\FF.bmp"));
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<String, Object>();
        //@RequestParam()请求的参数
        body.add("multipartFile", resource);

        HttpEntity<MultiValueMap<String, Object>> multiValueMapHttpEntity = new HttpEntity<MultiValueMap<String, Object>>(body, headers);
//指定 restTemplate当遇到400或401响应时候也不要抛出异常,也要正常返回值
        restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
            @Override
            public void handleError(ClientHttpResponse response) throws IOException {
                //当响应的值为400或401时候也要正常响应,不要抛出异常
                if (response.getRawStatusCode() != 400 && response.getRawStatusCode() != 401) {
                    super.handleError(response);
                }
            }
        });

//                                                                   url:去寻找Eureka负载均衡查找地址
//                                                                      HttpMethod.POST:请求方式
//                                                                          multiValueMapHttpEntity:给对方的数据
//                                                                              Map.class:以什么数据接收返回数据

        ResponseEntity<Object> exchange = restTemplate.exchange(url, HttpMethod.POST, multiValueMapHttpEntity, Object.class);

        Object o = exchange.getBody(); //返回的数据
        System.out.println(o);

    }

}


3.7 入参为javaBean对象且内部有 MultipartFile属性 请求方式

  • 入参有附件 请求头headers 必须设置 “content-type=multipart/form-data”
  • 请求头为content-type=multipart/form-data 不能使用 @RequestBody注解接收
  • @RequestBody 注解标识,通常会用application/json, application/xml处理content-type

import com.it.mhh.restTemplate.entitiy.User;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.util.Map;
import java.util.Objects;

/**
 * @创建人: Mhh
 * @创建时间: 2022/1/6
 * @描述:
 */
@RestController
@RequestMapping("restTemplate")
public class RestTemplateController {

    
    @PostMapping(value = "multipartFile", headers = "content-type=multipart/form-data")
    public void multipartFile(@RequestParam("multipartFile") MultipartFile multipartFile) {

        try {
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(Objects.requireNonNull(multipartFile.getOriginalFilename())));
            InputStream inputStream = multipartFile.getInputStream();
            int len;
            byte[] bytes = new byte[1024];
            while ((len = inputStream.read(bytes)) != -1) {
                bufferedOutputStream.write(bytes, 0, len);
                bufferedOutputStream.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}    


application.yml配置

  • 附件过大传不过去可配置上传大小(默认1MB)
spring:
  servlet:
    multipart:
      max-file-size: 10MB #设置单个文件的大小
      max-request-size: 10MB #设置单次请求的文件的总大小


javaBean User对象配置

  • 用于测试入参为实体对象的简单javaBean
import lombok.Data;
import org.springframework.web.multipart.MultipartFile;

/**
 * @创建人: Mhh
 * @创建时间: 2022/1/14
 * @描述:
 */
@Data
public class User {
    private String name;
    private MultipartFile multipartFile;
}



入参为javaBean对象且内部有 MultipartFile属性 请求方式 测试结果:

  • ResponseEntity exchange(String url, HttpMethod method, @Nullable HttpEntity<?> requestEntity, Class responseType, Object… uriVariables)
                   url: 请求路径
                   method: 请求方式(POST/GET…)
                   requestEntity: 给对方传递的的数据
                   responseType:返回对象类型
                   uriVariables: 表示 url地址上传递的值(适用于restful风格)
    在这里插入图片描述
    在这里插入图片描述
import cn.hutool.json.JSONUtil;
import com.it.mhh.restTemplate.entitiy.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

/**
 * @创建人: Mhh
 * @创建时间: 2022/1/6
 * @描述:
 */
@SpringBootTest
@RunWith(SpringRunner.class)
public class RestTemplateTest {


    @Autowired
    RestTemplate restTemplate;



 /**
     * @return void
     * @explain : 入参为实体请求方式
     * @Author Mhh
     * @Date 2022/1/14 15:33
     */

    @Test
    public void user() {
        String url = "http://127.0.0.1:8080/restTemplate/user";
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();

//        headers.add("authorization", "Bearer 774720e6-8193-48b9-9fb0-7f0591ffbeef");
//        headers.add("content-type", "application/json");
        FileSystemResource resource = new FileSystemResource(new File("D:\\JAVAWEB.jpg"));
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<String, Object>();
       
        body.add("multipartFile", resource);
        body.add("name", resource.getFilename());

        HttpEntity<MultiValueMap<String, Object>> multiValueMapHttpEntity = new HttpEntity<MultiValueMap<String, Object>>(body, headers);
//指定 restTemplate当遇到400或401响应时候也不要抛出异常,也要正常返回值
        restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
            @Override
            public void handleError(ClientHttpResponse response) throws IOException {
                //当响应的值为400或401时候也要正常响应,不要抛出异常
                if (response.getRawStatusCode() != 400 && response.getRawStatusCode() != 401) {
                    super.handleError(response);
                }
            }
        });

//                                                                   url:去寻找Eureka负载均衡查找地址
//                                                                      HttpMethod.POST:请求方式
//                                                                          multiValueMapHttpEntity:给对方的数据
//                                                                              Map.class:以什么数据接收返回数据

        ResponseEntity<User> exchange = restTemplate.exchange(url, HttpMethod.POST, multiValueMapHttpEntity, User.class);

        User user = exchange.getBody(); //返回的数据
        System.err.println(user);

    }



}









链接:SpringBoot之RestTemplate 简单常用使用示例 源代码下载地址

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Spring Boot中的RestTemplate是一个用于发送HTTP请求的客户端工具。它可以与各种类型的RESTful服务进行交互,并支持多种HTTP方法(如GET、POST、PUT、DELETE等)。 使用RestTemplate,您可以发送HTTP请求并获取服务器返回的响应。它提供了一组方便的方法,用于处理请求和响应的各个方面,如请求头、请求体、路径参数、查询参数等。 下面是一个简单示例,展示了如何使用RestTemplate发送GET请求: ```java RestTemplate restTemplate = new RestTemplate(); String url = "https://api.example.com/users/{id}"; String id = "123"; User user = restTemplate.getForObject(url, User.class, id); ``` 在上面的示例中,我们创建了一个RestTemplate实例,并指定了要发送请求的URL。我们还定义了一个路径参数`{id}`,并使用`restTemplate.getForObject()`方法发送GET请求。将服务器返回的JSON响应映射到一个User对象。 除了GET请求,RestTemplate还支持其他HTTP方法,如POST、PUT和DELETE。您可以使用不同的方法来发送不同类型的请求,并在需要时设置请求头、请求体等。 要使用RestTemplate,在Spring Boot项目中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> ``` 这将自动包含RestTemplate所需的所有依赖项,并使其可用于您的应用程序。 总结起来,RestTemplate是一个强大且易于使用的HTTP客户端工具,适用于与RESTful服务进行通信。它是Spring Boot中常用的组件之一,可以简化HTTP请求的处理过程。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

孟浩浩

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值