SpringBoot之RestTemplate 简单常用使用示例

目录

  • 1.引入pom依赖
  • 2.配置启动类并 注入RestTemplate实体
  • 3. RestTemplate 简单常用使用示例
    • 3.1 入参为空的请求方式
      • 入参为空的请求方式测试结果:
    • 3.2 入参为@RequestParam() 请求方式
      • 入参为@RequestParam() 请求方式测试结果:
    • 3.3 入参为@RequestBody 请求方式
      • 入参为@RequestBody 请求方式测试结果:
    • 3.4 入参为@RequestParam()与@RequestBody 请求方式
      • 入参为@RequestParam()与@RequestBody 请求方式测试结果:
    • 3.5 入参为@PathVariable 请求方式
      • 入参为@PathVariable 请求方式测试结果:
    • 3.6 入参为MultipartFile 附件 请求方式
      • application.yml配置
      • 入参为MultipartFile 附件 请求方式测试结果:
    • 3.7 入参为javaBean对象且内部有 MultipartFile属性 请求方式
      • application.yml配置
      • javaBean User对象配置
      • 入参为javaBean对象且内部有 MultipartFile属性 请求方式 测试结果:
  • 链接:[SpringBoot之RestTemplate 简单常用使用示例 源代码下载地址](https://download.csdn.net/download/JAVA_MHH/76476726)

1.引入pom依赖

  • 引入SpringBoot和SpringCloud版本时特别注意下他们的兼容
    参考: https://spring.io/projects/spring-cloud.
 <!--引入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 : 请求路径 SpringBoot之RestTemplate 简单常用使用示例_第1张图片
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 headers = new LinkedMultiValueMap();
        headers.add("请求头", "value值");
//        MultiValueMap body = new LinkedMultiValueMap();
        @RequestParam()请求的参数
        body.add("body键", "body值");
//        HttpEntity> multiValueMapHttpEntity = new HttpEntity>(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 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 : 请求路径
    SpringBoot之RestTemplate 简单常用使用示例_第2张图片
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 body = new LinkedMultiValueMap();
        //@RequestParam()请求的参数
        body.add("id", "1234");
        body.add("age", 11);

        HttpEntity> multiValueMapHttpEntity = new HttpEntity>(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 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 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风格)
    SpringBoot之RestTemplate 简单常用使用示例_第3张图片
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 body = new LinkedMultiValueMap();
        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风格)
    SpringBoot之RestTemplate 简单常用使用示例_第4张图片
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 body = new LinkedMultiValueMap();
        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风格)
    SpringBoot之RestTemplate 简单常用使用示例_第5张图片
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风格)
    SpringBoot之RestTemplate 简单常用使用示例_第6张图片
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风格)
    SpringBoot之RestTemplate 简单常用使用示例_第7张图片
    SpringBoot之RestTemplate 简单常用使用示例_第8张图片
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 简单常用使用示例 源代码下载地址

你可能感兴趣的:(SpringBoot,spring,boot,java,后端)