RestTemplateUtils工具类

Spring 远程调用Rest服务工具类,包含Get、Post、Put、Delete四种调用方式。

依赖jar

    
        org.springframework
        spring-context
        5.0.9.RELEASE
    
    
        org.springframework
        spring-web
        5.0.9.RELEASE
    

复制代码

RestTemplateUtils.java
复制代码

package javax.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  ResponseEntity get(String url, Class responseType) {
    return restTemplate.getForEntity(url, responseType);
}

/**
 * GET请求调用方式
 * 
 * @param url 请求URL
 * @param responseType 返回对象类型
 * @param uriVariables URL中的变量,按顺序依次对应
 * @return ResponseEntity 响应对象封装类
 */
public static  ResponseEntity get(String url, Class responseType, Object... uriVariables) {
    return restTemplate.getForEntity(url, responseType, uriVariables);
}

/**
 * GET请求调用方式
 * 
 * @param url 请求URL
 * @param responseType 返回对象类型
 * @param uriVariables URL中的变量,与Map中的key对应
 * @return ResponseEntity 响应对象封装类
 */
public static  ResponseEntity get(String url, Class responseType, Map uriVariables) {
    return restTemplate.getForEntity(url, responseType, uriVariables);
}

/**
 * 带请求头的GET请求调用方式
 * 
 * @param url 请求URL
 * @param headers 请求头参数
 * @param responseType 返回对象类型
 * @param uriVariables URL中的变量,按顺序依次对应
 * @return ResponseEntity 响应对象封装类
 */
public static  ResponseEntity get(String url, Map headers, Class 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  ResponseEntity get(String url, HttpHeaders headers, Class 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  ResponseEntity get(String url, Map headers, Class responseType, Map 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  ResponseEntity get(String url, HttpHeaders headers, Class responseType, Map uriVariables) {
    HttpEntity requestEntity = new HttpEntity<>(headers);
    return exchange(url, HttpMethod.GET, requestEntity, responseType, uriVariables);
}

// ----------------------------------POST-------------------------------------------------------

/**
 * POST请求调用方式
 * 
 * @param url 请求URL
 * @param responseType 返回对象类型
 * @return
 */
public static  ResponseEntity post(String url, Class responseType) {
    return restTemplate.postForEntity(url, HttpEntity.EMPTY, responseType);
}

/**
 * POST请求调用方式
 * 
 * @param url 请求URL
 * @param requestBody 请求参数体
 * @param responseType 返回对象类型
 * @return ResponseEntity 响应对象封装类
 */
public static  ResponseEntity post(String url, Object requestBody, Class responseType) {
    return restTemplate.postForEntity(url, requestBody, responseType);
}

/**
 * POST请求调用方式
 * 
 * @param url 请求URL
 * @param requestBody 请求参数体
 * @param responseType 返回对象类型
 * @param uriVariables URL中的变量,按顺序依次对应
 * @return ResponseEntity 响应对象封装类
 */
public static  ResponseEntity post(String url, Object requestBody, Class 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  ResponseEntity post(String url, Object requestBody, Class responseType, Map 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  ResponseEntity post(String url, Map headers, Object requestBody, Class 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  ResponseEntity post(String url, HttpHeaders headers, Object requestBody, Class responseType, Object... uriVariables) {
    HttpEntity requestEntity = new HttpEntity(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  ResponseEntity post(String url, Map headers, Object requestBody, Class responseType, Map 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  ResponseEntity post(String url, HttpHeaders headers, Object requestBody, Class responseType, Map uriVariables) {
    HttpEntity requestEntity = new HttpEntity(requestBody, headers);
    return post(url, requestEntity, responseType, uriVariables);
}

/**
 * 自定义请求头和请求体的POST请求调用方式
 * 
 * @param url 请求URL
 * @param requestEntity 请求头和请求体封装对象
 * @param responseType 返回对象类型
 * @param uriVariables URL中的变量,按顺序依次对应
 * @return ResponseEntity 响应对象封装类
 */
public static  ResponseEntity post(String url, HttpEntity requestEntity, Class 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  ResponseEntity post(String url, HttpEntity requestEntity, Class responseType, Map uriVariables) {
    return restTemplate.exchange(url, HttpMethod.POST, requestEntity, responseType, uriVariables);
}

// ----------------------------------PUT-------------------------------------------------------

/**
 * PUT请求调用方式
 * 
 * @param url 请求URL
 * @param responseType 返回对象类型
 * @param uriVariables URL中的变量,按顺序依次对应
 * @return ResponseEntity 响应对象封装类
 */
public static  ResponseEntity put(String url, Class responseType, Object... uriVariables) {
    return put(url, HttpEntity.EMPTY, responseType, uriVariables);
}

/**
 * PUT请求调用方式
 * 
 * @param url 请求URL
 * @param requestBody 请求参数体
 * @param responseType 返回对象类型
 * @param uriVariables URL中的变量,按顺序依次对应
 * @return ResponseEntity 响应对象封装类
 */
public static  ResponseEntity put(String url, Object requestBody, Class responseType, Object... uriVariables) {
    HttpEntity requestEntity = new HttpEntity(requestBody);
    return put(url, requestEntity, responseType, uriVariables);
}

/**
 * PUT请求调用方式
 * 
 * @param url 请求URL
 * @param requestBody 请求参数体
 * @param responseType 返回对象类型
 * @param uriVariables URL中的变量,与Map中的key对应
 * @return ResponseEntity 响应对象封装类
 */
public static  ResponseEntity put(String url, Object requestBody, Class responseType, Map uriVariables) {
    HttpEntity requestEntity = new HttpEntity(requestBody);
    return put(url, requestEntity, responseType, uriVariables);
}

/**
 * 带请求头的PUT请求调用方式
 * 
 * @param url 请求URL
 * @param headers 请求头参数
 * @param requestBody 请求参数体
 * @param responseType 返回对象类型
 * @param uriVariables URL中的变量,按顺序依次对应
 * @return ResponseEntity 响应对象封装类
 */
public static  ResponseEntity put(String url, Map headers, Object requestBody, Class responseType, Object... uriVariables) {
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setAll(headers);
    return put(url, httpHeaders, requestBody, responseType, uriVariables);
}

/**
 * 带请求头的PUT请求调用方式
 * 
 * @param url 请求URL
 * @param headers 请求头参数
 * @param requestBody 请求参数体
 * @param responseType 返回对象类型
 * @param uriVariables URL中的变量,按顺序依次对应
 * @return ResponseEntity 响应对象封装类
 */
public static  ResponseEntity put(String url, HttpHeaders headers, Object requestBody, Class responseType, Object... uriVariables) {
    HttpEntity requestEntity = new HttpEntity(requestBody, headers);
    return put(url, requestEntity, responseType, uriVariables);
}

/**
 * 带请求头的PUT请求调用方式
 * 
 * @param url 请求URL
 * @param headers 请求头参数
 * @param requestBody 请求参数体
 * @param responseType 返回对象类型
 * @param uriVariables URL中的变量,与Map中的key对应
 * @return ResponseEntity 响应对象封装类
 */
public static  ResponseEntity put(String url, Map headers, Object requestBody, Class responseType, Map uriVariables) {
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setAll(headers);
    return put(url, httpHeaders, requestBody, responseType, uriVariables);
}

/**
 * 带请求头的PUT请求调用方式
 * 
 * @param url 请求URL
 * @param headers 请求头参数
 * @param requestBody 请求参数体
 * @param responseType 返回对象类型
 * @param uriVariables URL中的变量,与Map中的key对应
 * @return ResponseEntity 响应对象封装类
 */
public static  ResponseEntity put(String url, HttpHeaders headers, Object requestBody, Class responseType, Map uriVariables) {
    HttpEntity requestEntity = new HttpEntity(requestBody, headers);
    return put(url, requestEntity, responseType, uriVariables);
}

/**
 * 自定义请求头和请求体的PUT请求调用方式
 * 
 * @param url 请求URL
 * @param requestEntity 请求头和请求体封装对象
 * @param responseType 返回对象类型
 * @param uriVariables URL中的变量,按顺序依次对应
 * @return ResponseEntity 响应对象封装类
 */
public static  ResponseEntity put(String url, HttpEntity requestEntity, Class responseType, Object... uriVariables) {
    return restTemplate.exchange(url, HttpMethod.PUT, requestEntity, responseType, uriVariables);
}

/**
 * 自定义请求头和请求体的PUT请求调用方式
 * 
 * @param url 请求URL
 * @param requestEntity 请求头和请求体封装对象
 * @param responseType 返回对象类型
 * @param uriVariables URL中的变量,与Map中的key对应
 * @return ResponseEntity 响应对象封装类
 */
public static  ResponseEntity put(String url, HttpEntity requestEntity, Class responseType, Map uriVariables) {
    return restTemplate.exchange(url, HttpMethod.PUT, requestEntity, responseType, uriVariables);
}

// ----------------------------------DELETE-------------------------------------------------------

/**
 * DELETE请求调用方式
 * 
 * @param url 请求URL
 * @param responseType 返回对象类型
 * @param uriVariables URL中的变量,按顺序依次对应
 * @return ResponseEntity 响应对象封装类
 */
public static  ResponseEntity delete(String url, Class responseType, Object... uriVariables) {
    return delete(url, HttpEntity.EMPTY, responseType, uriVariables);
}

/**
 * DELETE请求调用方式
 * 
 * @param url 请求URL
 * @param responseType 返回对象类型
 * @param uriVariables URL中的变量,与Map中的key对应
 * @return ResponseEntity 响应对象封装类
 */
public static  ResponseEntity delete(String url, Class responseType, Map uriVariables) {
    return delete(url, HttpEntity.EMPTY, responseType, uriVariables);
}

/**
 * DELETE请求调用方式
 * 
 * @param url 请求URL
 * @param requestBody 请求参数体
 * @param responseType 返回对象类型
 * @param uriVariables URL中的变量,按顺序依次对应
 * @return ResponseEntity 响应对象封装类
 */
public static  ResponseEntity delete(String url, Object requestBody, Class responseType, Object... uriVariables) {
    HttpEntity requestEntity = new HttpEntity(requestBody);
    return delete(url, requestEntity, responseType, uriVariables);
}

/**
 * DELETE请求调用方式
 * 
 * @param url 请求URL
 * @param requestBody 请求参数体
 * @param responseType 返回对象类型
 * @param uriVariables URL中的变量,与Map中的key对应
 * @return ResponseEntity 响应对象封装类
 */
public static  ResponseEntity delete(String url, Object requestBody, Class responseType, Map uriVariables) {
    HttpEntity requestEntity = new HttpEntity(requestBody);
    return delete(url, requestEntity, responseType, uriVariables);
}

/**
 * 带请求头的DELETE请求调用方式
 * 
 * @param url 请求URL
 * @param headers 请求头参数
 * @param responseType 返回对象类型
 * @param uriVariables URL中的变量,按顺序依次对应
 * @return ResponseEntity 响应对象封装类
 */
public static  ResponseEntity delete(String url, Map headers, Class responseType, Object... uriVariables) {
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setAll(headers);
    return delete(url, httpHeaders, responseType, uriVariables);
}

/**
 * 带请求头的DELETE请求调用方式
 * 
 * @param url 请求URL
 * @param headers 请求头参数
 * @param responseType 返回对象类型
 * @param uriVariables URL中的变量,按顺序依次对应
 * @return ResponseEntity 响应对象封装类
 */
public static  ResponseEntity delete(String url, HttpHeaders headers, Class responseType, Object... uriVariables) {
    HttpEntity requestEntity = new HttpEntity(headers);
    return delete(url, requestEntity, responseType, uriVariables);
}

/**
 * 带请求头的DELETE请求调用方式
 * 
 * @param url 请求URL
 * @param headers 请求头参数
 * @param responseType 返回对象类型
 * @param uriVariables URL中的变量,与Map中的key对应
 * @return ResponseEntity 响应对象封装类
 */
public static  ResponseEntity delete(String url, Map headers, Class responseType, Map uriVariables) {
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setAll(headers);
    return delete(url, httpHeaders, responseType, uriVariables);
}

/**
 * 带请求头的DELETE请求调用方式
 * 
 * @param url 请求URL
 * @param headers 请求头参数
 * @param responseType 返回对象类型
 * @param uriVariables URL中的变量,与Map中的key对应
 * @return ResponseEntity 响应对象封装类
 */
public static  ResponseEntity delete(String url, HttpHeaders headers, Class responseType, Map uriVariables) {
    HttpEntity requestEntity = new HttpEntity(headers);
    return delete(url, requestEntity, responseType, uriVariables);
}

/**
 * 带请求头的DELETE请求调用方式
 * 
 * @param url 请求URL
 * @param headers 请求头参数
 * @param requestBody 请求参数体
 * @param responseType 返回对象类型
 * @param uriVariables URL中的变量,按顺序依次对应
 * @return ResponseEntity 响应对象封装类
 */
public static  ResponseEntity delete(String url, Map headers, Object requestBody, Class responseType, Object... uriVariables) {
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setAll(headers);
    return delete(url, httpHeaders, requestBody, responseType, uriVariables);
}

/**
 * 带请求头的DELETE请求调用方式
 * 
 * @param url 请求URL
 * @param headers 请求头参数
 * @param requestBody 请求参数体
 * @param responseType 返回对象类型
 * @param uriVariables URL中的变量,按顺序依次对应
 * @return ResponseEntity 响应对象封装类
 */
public static  ResponseEntity delete(String url, HttpHeaders headers, Object requestBody, Class responseType, Object... uriVariables) {
    HttpEntity requestEntity = new HttpEntity(requestBody, headers);
    return delete(url, requestEntity, responseType, uriVariables);
}

/**
 * 带请求头的DELETE请求调用方式
 * 
 * @param url 请求URL
 * @param headers 请求头参数
 * @param requestBody 请求参数体
 * @param responseType 返回对象类型
 * @param uriVariables URL中的变量,与Map中的key对应
 * @return ResponseEntity 响应对象封装类
 */
public static  ResponseEntity delete(String url, Map headers, Object requestBody, Class responseType, Map uriVariables) {
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setAll(headers);
    return delete(url, httpHeaders, requestBody, responseType, uriVariables);
}

/**
 * 带请求头的DELETE请求调用方式
 * 
 * @param url 请求URL
 * @param headers 请求头参数
 * @param requestBody 请求参数体
 * @param responseType 返回对象类型
 * @param uriVariables URL中的变量,与Map中的key对应
 * @return ResponseEntity 响应对象封装类
 */
public static  ResponseEntity delete(String url, HttpHeaders headers, Object requestBody, Class responseType, Map uriVariables) {
    HttpEntity requestEntity = new HttpEntity(requestBody, headers);
    return delete(url, requestEntity, responseType, uriVariables);
}

/**
 * 自定义请求头和请求体的DELETE请求调用方式
 * 
 * @param url 请求URL
 * @param requestEntity 请求头和请求体封装对象
 * @param responseType 返回对象类型
 * @param uriVariables URL中的变量,按顺序依次对应
 * @return ResponseEntity 响应对象封装类
 */
public static  ResponseEntity delete(String url, HttpEntity requestEntity, Class responseType, Object... uriVariables) {
    return restTemplate.exchange(url, HttpMethod.DELETE, requestEntity, responseType, uriVariables);
}

/**
 * 自定义请求头和请求体的DELETE请求调用方式
 * 
 * @param url 请求URL
 * @param requestEntity 请求头和请求体封装对象
 * @param responseType 返回对象类型
 * @param uriVariables URL中的变量,与Map中的key对应
 * @return ResponseEntity 响应对象封装类
 */
public static  ResponseEntity delete(String url, HttpEntity requestEntity, Class responseType, Map uriVariables) {
    return restTemplate.exchange(url, HttpMethod.DELETE, requestEntity, responseType, uriVariables);
}

// ----------------------------------通用方法-------------------------------------------------------

/**
 * 通用调用方式
 * 
 * @param url 请求URL
 * @param method 请求方法类型
 * @param requestEntity 请求头和请求体封装对象
 * @param responseType 返回对象类型
 * @param uriVariables URL中的变量,按顺序依次对应
 * @return ResponseEntity 响应对象封装类
 */
public static  ResponseEntity exchange(String url, HttpMethod method, HttpEntity requestEntity, Class 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  ResponseEntity exchange(String url, HttpMethod method, HttpEntity requestEntity, Class responseType, Map 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.ArrayList;
import java.util.HashMap;
import java.util.List;
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 {

/**
 * 测试HTTPS请求访问博客园
 */
@Test
public void test() {
    String url = "https://www.cnblogs.com/{id}/p/{pageName}.html";
    String id = "jonban";
    List pages = new ArrayList<>();
    pages.add("rest");
    pages.add("jsoup");
    pages.add("sms");
    pages.add("rememberMe");
    pages.add("properties");
    pages.add("async");

    for (String pageName : pages) {
        ResponseEntity entity = RestTemplateUtils.get(url, String.class, id, pageName);
        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 headers = new HashMap<>();
    headers.put("appId", "Basic MyAppId");
    ResponseEntity 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 requestBody = new LinkedMultiValueMap<>();
    requestBody.add("name", "Logan");
    requestBody.add("age", 12);
    ResponseEntity 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 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 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 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 response = RestTemplateUtils.get(url, byte[].class, filePath, fileName);
        System.out.println(response.getStatusCode());
        System.out.println(response.getHeaders().getContentType());

        // 如果返回时文本内容,则直接输出
        if ("text/html;charset=UTF-8".equals(response.getHeaders().getContentType().toString())) {
            System.out.println(new String(response.getBody(), "UTF-8"));
        }

        // 输出响应内容到本地文件
        else {

            File file = new File("G:\\Temp\\Test", fileName);
            if (HttpStatus.OK.equals(response.getStatusCode())) {
                FileUtils.writeByteArrayToFile(file, response.getBody());
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

}

/**
 * 测试下载阿里巴巴的fastjson-1.2.56.jar
 */
@Test
public void downloadFile2() {
    try {
        String url = "http://central.maven.org/maven2/com/alibaba/fastjson/1.2.56/fastjson-1.2.56.jar";

        ResponseEntity 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
    复制代码

4.0.0
com.java
test-server
1.0.0


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





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


    
        commons-fileupload
        commons-fileupload
        1.3.3
    
    
        com.alibaba
        fastjson
        1.2.56
    



    
    
        org.springframework
        springloaded
        1.2.8.RELEASE
    
    
        org.springframework.boot
        spring-boot-devtools
    




    ${project.artifactId}
    
        
            org.apache.maven.plugins
            maven-compiler-plugin
            
                1.8
                1.8
                UTF-8
            
        

        
            org.springframework.boot
            spring-boot-maven-plugin
            
                
                    
                        repackage
                    
                
            
        
    

复制代码

  1. 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);
}

}

复制代码

  1. 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 + "]";
}

}

复制代码

  1. 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;
}

}

复制代码

  1. 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.net.URLEncoder;
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 uploadFile(@RequestParam(required = true) CommonsMultipartFile file, @RequestParam(required = true) CommonsMultipartFile file2, String uploadPath) {
    Map result = new HashMap();
    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 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);
        ) {

            // 对文件名进行URL转义,防止中文乱码
            fileName = URLEncoder.encode(fileName, "UTF-8");

            // 空格用URLEncoder.encode转义后会变成"+",所以要替换成"%20",浏览器会解码回空格
            fileName = fileName.replace("+", "%20");

            // "+"用URLEncoder.encode转义后会变成"%2B",所以要替换成"+",浏览器会解码回"+"
            fileName = fileName.replace("%2B", "+");
            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();
        }
    }

}

}

  1. 运行 TestServerStarter.java ,启动测试服务器。

运行RestTest.java 类中对应的测试方法,可以测试对应功能,各种情况典型示例已给出。

你可能感兴趣的:(SpringBoot)