Spring 远程调用工具类RestTemplateUtils
作者:互联网
RestTemplateUtils.java
package utils; import java.util.Map; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; /** * RestTemplate 远程调用工具类 * * @author Logan * @createDate 2019-02-08 * */ public class RestTemplateUtils { private static final RestTemplate restTemplate = new RestTemplate(); // ----------------------------------GET------------------------------------------------------- /** * GET请求调用方式 * * @param url 请求URL * @param responseType 返回对象类型 * @return ResponseEntity 响应对象封装类 */ public static <T> ResponseEntity<T> get(String url, Class<T> responseType) { return restTemplate.getForEntity(url, responseType); } /** * GET请求调用方式 * * @param url 请求URL * @param responseType 返回对象类型 * @param uriVariables URL中的变量,按顺序依次对应 * @return ResponseEntity 响应对象封装类 */ public static <T> ResponseEntity<T> get(String url, Class<T> responseType, Object... uriVariables) { return restTemplate.getForEntity(url, responseType, uriVariables); } /** * GET请求调用方式 * * @param url 请求URL * @param responseType 返回对象类型 * @param uriVariables URL中的变量,与Map中的key对应 * @return ResponseEntity 响应对象封装类 */ public static <T> ResponseEntity<T> get(String url, Class<T> responseType, Map<String, ?> uriVariables) { return restTemplate.getForEntity(url, responseType, uriVariables); } /** * 带请求头的GET请求调用方式 * * @param url 请求URL * @param headers 请求头参数 * @param responseType 返回对象类型 * @param uriVariables URL中的变量,按顺序依次对应 * @return ResponseEntity 响应对象封装类 */ public static <T> ResponseEntity<T> get(String url, Map<String, String> headers, Class<T> responseType, Object... uriVariables) { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setAll(headers); return get(url, httpHeaders, responseType, uriVariables); } /** * 带请求头的GET请求调用方式 * * @param url 请求URL * @param headers 请求头参数 * @param responseType 返回对象类型 * @param uriVariables URL中的变量,按顺序依次对应 * @return ResponseEntity 响应对象封装类 */ public static <T> ResponseEntity<T> get(String url, HttpHeaders headers, Class<T> responseType, Object... uriVariables) { HttpEntity<?> requestEntity = new HttpEntity<>(headers); return exchange(url, HttpMethod.GET, requestEntity, responseType, uriVariables); } /** * 带请求头的GET请求调用方式 * * @param url 请求URL * @param headers 请求头参数 * @param responseType 返回对象类型 * @param uriVariables URL中的变量,与Map中的key对应 * @return ResponseEntity 响应对象封装类 */ public static <T> ResponseEntity<T> get(String url, Map<String, String> headers, Class<T> responseType, Map<String, ?> uriVariables) { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setAll(headers); return get(url, httpHeaders, responseType, uriVariables); } /** * 带请求头的GET请求调用方式 * * @param url 请求URL * @param headers 请求头参数 * @param responseType 返回对象类型 * @param uriVariables URL中的变量,与Map中的key对应 * @return ResponseEntity 响应对象封装类 */ public static <T> ResponseEntity<T> get(String url, HttpHeaders headers, Class<T> responseType, Map<String, ?> uriVariables) { HttpEntity<?> requestEntity = new HttpEntity<>(headers); return exchange(url, HttpMethod.GET, requestEntity, responseType, uriVariables); } // ----------------------------------POST------------------------------------------------------- /** * POST请求调用方式 * * @param url 请求URL * @param requestBody 请求参数体 * @param responseType 返回对象类型 * @return ResponseEntity 响应对象封装类 */ public static <T> ResponseEntity<T> post(String url, Object requestBody, Class<T> responseType) { return restTemplate.postForEntity(url, requestBody, responseType); } /** * POST请求调用方式 * * @param url 请求URL * @param requestBody 请求参数体 * @param responseType 返回对象类型 * @param uriVariables URL中的变量,按顺序依次对应 * @return ResponseEntity 响应对象封装类 */ public static <T> ResponseEntity<T> post(String url, Object requestBody, Class<T> responseType, Object... uriVariables) { return restTemplate.postForEntity(url, requestBody, responseType, uriVariables); } /** * POST请求调用方式 * * @param url 请求URL * @param requestBody 请求参数体 * @param responseType 返回对象类型 * @param uriVariables URL中的变量,与Map中的key对应 * @return ResponseEntity 响应对象封装类 */ public static <T> ResponseEntity<T> post(String url, Object requestBody, Class<T> responseType, Map<String, ?> uriVariables) { return restTemplate.postForEntity(url, requestBody, responseType, uriVariables); } /** * 带请求头的POST请求调用方式 * * @param url 请求URL * @param headers 请求头参数 * @param requestBody 请求参数体 * @param responseType 返回对象类型 * @param uriVariables URL中的变量,按顺序依次对应 * @return ResponseEntity 响应对象封装类 */ public static <T> ResponseEntity<T> post(String url, Map<String, String> headers, Object requestBody, Class<T> responseType, Object... uriVariables) { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setAll(headers); return post(url, httpHeaders, requestBody, responseType, uriVariables); } /** * 带请求头的POST请求调用方式 * * @param url 请求URL * @param headers 请求头参数 * @param requestBody 请求参数体 * @param responseType 返回对象类型 * @param uriVariables URL中的变量,按顺序依次对应 * @return ResponseEntity 响应对象封装类 */ public static <T> ResponseEntity<T> post(String url, HttpHeaders headers, Object requestBody, Class<T> responseType, Object... uriVariables) { HttpEntity<Object> requestEntity = new HttpEntity<Object>(requestBody, headers); return post(url, requestEntity, responseType, uriVariables); } /** * 带请求头的POST请求调用方式 * * @param url 请求URL * @param headers 请求头参数 * @param requestBody 请求参数体 * @param responseType 返回对象类型 * @param uriVariables URL中的变量,与Map中的key对应 * @return ResponseEntity 响应对象封装类 */ public static <T> ResponseEntity<T> post(String url, Map<String, String> headers, Object requestBody, Class<T> responseType, Map<String, ?> uriVariables) { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setAll(headers); return post(url, httpHeaders, requestBody, responseType, uriVariables); } /** * 带请求头的POST请求调用方式 * * @param url 请求URL * @param headers 请求头参数 * @param requestBody 请求参数体 * @param responseType 返回对象类型 * @param uriVariables URL中的变量,与Map中的key对应 * @return ResponseEntity 响应对象封装类 */ public static <T> ResponseEntity<T> post(String url, HttpHeaders headers, Object requestBody, Class<T> responseType, Map<String, ?> uriVariables) { HttpEntity<Object> requestEntity = new HttpEntity<Object>(requestBody, headers); return post(url, requestEntity, responseType, uriVariables); } /** * 自定义请求头和请求体的POST请求调用方式 * * @param url 请求URL * @param requestEntity 请求头和请求体封装对象 * @param responseType 返回对象类型 * @param uriVariables URL中的变量,按顺序依次对应 * @return ResponseEntity 响应对象封装类 */ public static <T> ResponseEntity<T> post(String url, HttpEntity<?> requestEntity, Class<T> responseType, Object... uriVariables) { return restTemplate.exchange(url, HttpMethod.POST, requestEntity, responseType, uriVariables); } /** * 自定义请求头和请求体的POST请求调用方式 * * @param url 请求URL * @param requestEntity 请求头和请求体封装对象 * @param responseType 返回对象类型 * @param uriVariables URL中的变量,与Map中的key对应 * @return ResponseEntity 响应对象封装类 */ public static <T> ResponseEntity<T> post(String url, HttpEntity<?> requestEntity, Class<T> responseType, Map<String, ?> uriVariables) { return restTemplate.exchange(url, HttpMethod.POST, requestEntity, responseType, uriVariables); } // ----------------------------------通用方法------------------------------------------------------- /** * 通用调用方式 * * @param url 请求URL * @param method 请求方法类型 * @param requestEntity 请求头和请求体封装对象 * @param responseType 返回对象类型 * @param uriVariables URL中的变量,按顺序依次对应 * @return ResponseEntity 响应对象封装类 */ public static <T> ResponseEntity<T> exchange(String url, HttpMethod method, HttpEntity<?> requestEntity, Class<T> responseType, Object... uriVariables) { return restTemplate.exchange(url, method, requestEntity, responseType, uriVariables); } /** * 通用调用方式 * * @param url 请求URL * @param method 请求方法类型 * @param requestEntity 请求头和请求体封装对象 * @param responseType 返回对象类型 * @param uriVariables URL中的变量,与Map中的key对应 * @return ResponseEntity 响应对象封装类 */ public static <T> ResponseEntity<T> exchange(String url, HttpMethod method, HttpEntity<?> requestEntity, Class<T> responseType, Map<String, ?> uriVariables) { return restTemplate.exchange(url, method, requestEntity, responseType, uriVariables); } /** * 获取RestTemplate实例对象,可自由调用其方法 * * @return RestTemplate实例对象 */ public static RestTemplate getRestTemplate() { return restTemplate; } }
测试示例如下:
RestTest.java
package test; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.apache.commons.io.FileUtils; import org.junit.Test; import org.springframework.core.io.FileSystemResource; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import com.alibaba.fastjson.JSONObject; import utils.RestTemplateUtils; /** * RestTemplate 功能测试类 * * @author Logan * @createDate 2019-02-08 * */ public class RestTest { @Test public void test() { String url = "http://127.0.0.1:8080/test/{name}?age={age}"; String name = null; for (int age = 15; age < 25; age++) { name = "Jack" + age; ResponseEntity<String> entity = RestTemplateUtils.get(url, String.class, name, age); System.out.println(entity.getStatusCode()); System.out.println(entity.getBody()); } } /** * 测试带请求头参数Headers的GET请求,POST类似 */ @Test public void testHeaders() { String url = "http://127.0.0.1:8080/test/Logan?age=16"; Map<String, String> headers = new HashMap<>(); headers.put("appId", "Basic MyAppId"); ResponseEntity<String> entity = RestTemplateUtils.get(url, headers, String.class); System.out.println(entity.getStatusCode()); System.out.println(entity.getBody()); } /** * 测试普通表单参数的POST请求 */ @Test public void sayHello() { String url = "http://127.0.0.1:8080/test/sayHello"; MultiValueMap<String, Object> requestBody = new LinkedMultiValueMap<>(); requestBody.add("name", "Logan"); requestBody.add("age", 12); ResponseEntity<JSONObject> response = RestTemplateUtils.post(url, requestBody, JSONObject.class); System.out.println(response.getStatusCode()); System.out.println(response.getBody()); } /** * 测试JSON格式请求体Body方式POST请求 */ @Test public void sayHelloBody() { String url = "http://127.0.0.1:8080/test/sayHelloBody"; JSONObject requestBody = new JSONObject(); requestBody.put("name", "Logan"); requestBody.put("age", 16); ResponseEntity<JSONObject> response = RestTemplateUtils.post(url, requestBody, JSONObject.class); System.out.println(response.getStatusCode()); System.out.println(response.getBody()); } /** * 测试上传文件 */ @Test public void uploadFile() { String url = "http://127.0.0.1:8080/test/uploadFile"; MultiValueMap<String, Object> requestBody = new LinkedMultiValueMap<>(); requestBody.add("uploadPath", "G:\\Temp\\Test"); requestBody.add("file", new FileSystemResource("G:\\Java\\JavaStyle.xml")); requestBody.add("file2", new FileSystemResource("G:\\Java\\jad.exe")); ResponseEntity<JSONObject> response = RestTemplateUtils.post(url, requestBody, JSONObject.class); System.out.println(response.getStatusCode()); System.out.println(response.getBody()); } @Test public void downloadFile() { try { String url = "http://127.0.0.1:8080/test/downloadFile?filePath={filePath}&fileName={fileName}"; String filePath = "G:\\Java"; String fileName = "JavaStyle.xml"; ResponseEntity<byte[]> response = RestTemplateUtils.get(url, byte[].class, filePath, fileName); System.out.println(response.getStatusCode()); File file = new File("G:\\Temp\\Test\\" + fileName); if (HttpStatus.OK.equals(response.getStatusCode())) { FileUtils.writeByteArrayToFile(file, response.getBody()); } } catch (IOException e) { e.printStackTrace(); } } @Test public void downloadFile2() { try { String url = "http://central.maven.org/maven2/com/alibaba/fastjson/1.2.56/fastjson-1.2.56.jar"; ResponseEntity<byte[]> response = RestTemplateUtils.get(url, byte[].class); System.out.println(response.getStatusCode()); File file = new File("G:\\Temp\\Test\\fastjson-1.2.56.jar"); if (HttpStatus.OK.equals(response.getStatusCode())) { FileUtils.writeByteArrayToFile(file, response.getBody()); } } catch (IOException e) { e.printStackTrace(); } } }
测试远程服务器接口示例如下:
1. 新建Maven项目 test-server
2. pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.java</groupId> <artifactId>test-server</artifactId> <version>1.0.0</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.5.RELEASE</version> </parent> <dependencies> <!-- Spring Boot --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.3</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.56</version> </dependency> <!-- 热部署 --> <dependency> <groupId>org.springframework</groupId> <artifactId>springloaded</artifactId> <version>1.2.8.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> </dependency> </dependencies> <build> <finalName>${project.artifactId}</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> <encoding>UTF-8</encoding> </configuration> </plugin> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <executions> <execution> <goals> <goal>repackage</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project>
3. TestServerStarter.java
package com.java; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * 测试服务器主启动类 * * @author Logan * @createDate 2019-02-08 * */ @SpringBootApplication public class TestServerStarter { public static void main(String[] args) { SpringApplication.run(TestServerStarter.class, args); } }
4. Person.java
package com.java.entity; /** * 测试实体类 * * @author Logan * @createDate 2019-02-08 * */ public class Person { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Person [name=" + name + ", age=" + age + "]"; } }
5. UploadConfig.java
package com.java.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.multipart.commons.CommonsMultipartResolver; /** * 上传文件配置 * * @author Logan * @createDate 2019-02-08 * */ @Configuration public class UploadConfig { @Bean public CommonsMultipartResolver multipartResolver() { CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(); // 设置最大上传文件大小为4GB multipartResolver.setMaxUploadSize(4294967296l); return multipartResolver; } }
6. TestController.java
package com.java.controller; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.commons.CommonsMultipartFile; import com.java.entity.Person; /** * 测试服务器测试接口类 * * @author Logan * @createDate 2019-02-08 * */ @RestController @RequestMapping("/test") public class TestController { @Autowired private HttpServletRequest request; @GetMapping("/{name}") public Person test(@PathVariable("name") String name, int age) { String appId = request.getHeader("appId"); System.out.println("appId: " + appId); Person person = new Person(); person.setName(name); person.setAge(age); System.out.println(person); return person; } @PostMapping("/sayHello") public Person sayHello(Person person) { System.out.println(person); return person; } @PostMapping("/sayHelloBody") public Person sayHelloBody(@RequestBody Person person) { System.out.println(person); return person; } @RequestMapping("/uploadFile") public Map<String, Object> uploadFile(@RequestParam(required = true) CommonsMultipartFile file, @RequestParam(required = true) CommonsMultipartFile file2, String uploadPath) { Map<String, Object> result = new HashMap<String, Object>(); try { // 上傳文件 File path = new File(uploadPath); if (!path.isDirectory() || !path.exists()) { path.mkdirs(); } File outFile = new File(uploadPath, file.getOriginalFilename()); file.transferTo(outFile); File outFile2 = new File(uploadPath, file2.getOriginalFilename()); file2.transferTo(outFile2); List<String> files = new ArrayList<>(); files.add(outFile.getAbsolutePath()); files.add(outFile2.getAbsolutePath()); result.put("successful", true); result.put("files", files); } catch (Exception e) { e.printStackTrace(); result.put("successful", false); result.put("msg", e.getMessage()); } return result; } @GetMapping("/downloadFile") public void downloadFile(HttpServletResponse response, String filePath, String fileName) { File file = new File(filePath, fileName); if (file.exists() && file.isFile()) { try ( OutputStream out = response.getOutputStream(); FileInputStream in = new FileInputStream(file); ) { fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1"); response.setContentType("application/x-msdownload;charset=UTF-8"); response.setHeader("Content-Disposition", "attachment; filename=" + fileName); IOUtils.copy(in, out); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } // 无法下载时给出提示信息 else { response.setContentType("text/html; charset=UTF-8"); try ( PrintWriter writer = response.getWriter(); ) { writer.write("找不到对应文件,请确认后重试!"); writer.flush(); } catch (IOException e) { e.printStackTrace(); } } } }
7. 运行 TestServerStarter.java ,启动测试服务器。
运行RestTest.java 类中对应的测试方法,可以测试对应功能,各种情况典型示例已给出。
.
标签:responseType,调用,return,uriVariables,url,Spring,param,import,RestTemplateUtils 来源: https://www.cnblogs.com/jonban/p/rest.html