栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot之RestTemplate 简单常用使用示例

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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.

 
    
    
        org.springframework.boot
        spring-boot-starter-parent
        2.3.2.RELEASE
    

    
    
        UTF-8
        UTF-8
        1.8
        
        Hoxton.SR10
    
    
    
        
            
                org.springframework.cloud
                spring-cloud-dependencies
                ${spring-cloud.version}
                pom
                import
            
        
    

    
        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
        
            org.springframework.cloud
            spring-cloud-commons
        

        
        
            org.projectlombok
            lombok
        


        
        
            cn.hutool
            hutool-json
            4.1.21
        

        
        
            org.springframework.boot
            spring-boot-starter-test
        
        
            junit
            junit
        
    


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;


@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;


@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;


@SpringBootTest
@RunWith(SpringRunner.class)
public class RestTemplateTest {


    @Autowired
    RestTemplate restTemplate;

    
    @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 exchange = restTemplate.exchange(new RequestEntity(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;


@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;


@SpringBootTest
@RunWith(SpringRunner.class)
public class RestTemplateTest {


    @Autowired
    RestTemplate restTemplate;

    

    @Test
    public void requestParam() throws URISyntaxException {

//        
        String url = "http://127.0.0.1:8080/restTemplate/requestParam";



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

        

        //
        ResponseEntity exchange = restTemplate.exchange(new RequestEntity(HttpMethod.GET, new URI(url + "?id=12344&age=13")), String.class);
        String s = exchange.getBody(); //返回的数据
        System.err.println(s); //已通过并返回:-->requestParam方法入参 id为: 12344 age为: 13
//---------------------------------------------------------------------------------------------------------
        
//        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;


@RestController
@RequestMapping("restTemplate")
public class RestTemplateController {

    
    @PostMapping("requestBody")
    public Map requestBody(@RequestBody Map 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;


@SpringBootTest
@RunWith(SpringRunner.class)
public class RestTemplateTest {


    @Autowired
    RestTemplate restTemplate;


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

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

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

        HttpEntity multiValueMapHttpEntity = new HttpEntity(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);
                }
            }
        });

        ResponseEntity 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;


@RestController
@RequestMapping("restTemplate")
public class RestTemplateController {

    
    @PostMapping("requestBodyAndRequestParam")
    public Map requestBody(@RequestParam("name") String name, @RequestBody Map 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;


@SpringBootTest
@RunWith(SpringRunner.class)
public class RestTemplateTest {


    @Autowired
    RestTemplate restTemplate;


    

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

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

//MultiValueMap body = new linkedMultiValueMap();
        Map body = new HashMap();
        body.put("小白老师", 0);

        HttpEntity multiValueMapHttpEntity = new HttpEntity(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);
                }
            }
        });

        ResponseEntity 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;


@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;


@SpringBootTest
@RunWith(SpringRunner.class)
public class RestTemplateTest {


    @Autowired
    RestTemplate restTemplate;



    
    @Test
    public void restFul() {
        String url = "http://127.0.0.1:8080/restTemplate/{name}/restFul/{age}";

        //配置请求体
        MultiValueMap body = new linkedMultiValueMap();

        HttpEntity> multiValueMapHttpEntity = new HttpEntity>(body);
        
        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;


@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;


@SpringBootTest
@RunWith(SpringRunner.class)
public class RestTemplateTest {


    @Autowired
    RestTemplate restTemplate;



    

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

//        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 body = new linkedMultiValueMap();
        //@RequestParam()请求的参数
        body.add("multipartFile", resource);

        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, 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;


@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;


@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;


@SpringBootTest
@RunWith(SpringRunner.class)
public class RestTemplateTest {


    @Autowired
    RestTemplate restTemplate;



 

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

//        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 body = new linkedMultiValueMap();
       
        body.add("multipartFile", resource);
        body.add("name", resource.getFilename());

        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, User.class);

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

    }



}









链接:SpringBoot之RestTemplate 简单常用使用示例 源代码下载地址
转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号