RestTemplate是Spring提供的用于访问Rest服务的客户端,RestTemplate提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率。
我基于RestTemplate编写了一个工具类,方便使用。工具类提供之提供了GET、POST、DELETE请求方法,其他方法自行补充
- Application启动类中实例RestTemplate
@SpringBootApplication
@RestController
public class Application {
public static void main(String[] args) {
SpringApplication.run(ElasticApplication.class, args);
}
@Bean
public RestTemplate restTemplate() {
return new RestTemplate(new HttpComponentsClientHttpRequestFactory());
}
}
- RestTemplateUtils工具类
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* RestTemplate工具类
*
* @author Colin.Ye
* @version 1.0
* @ClassName RestTemplateUtils
* @date 2019/7/31
**/
@Component
public class RestTemplateUtils {
@Autowired
private RestTemplate restTemplate;
/**
* POST请求-JSON参数
*
* @param url
* @param params
* @param headers
* @return
*/
public T httpPostJson(String url, Map params, Map headers, Class clazz) {
HttpHeaders httpHeaders = new HttpHeaders();
if (headers != null) {
headers.forEach((o1, o2) -> httpHeaders.add(o1, o2));
}
// json方式传参
return restTemplate.postForObject(url, new HttpEntity(params, httpHeaders), clazz);
}
/**
* POST请求-FROM参数
*
* @param url
* @param params
* @param headers
* @return
*/
public T httpPostFrom(String url, Map params, Map headers, Class clazz) {
HttpHeaders httpHeaders = new HttpHeaders();
params = params == null ? new LinkedHashMap<>() : params;
if (headers != null) {
headers.forEach((o1, o2) -> httpHeaders.add(o1, o2));
}
MultiValueMap stringObjectLinkedMultiValueMap = new LinkedMultiValueMap<>();
params.forEach((o1, o2) -> stringObjectLinkedMultiValueMap.add(o1, o2));
// 表单方式传参
// json方式传参
return restTemplate.postForObject(url, new HttpEntity(stringObjectLinkedMultiValueMap, httpHeaders), clazz);
}
/**
* GET请求-?号参数
*
* @param url
* @param params
* @param headers
* @return
*/
public T httpGetTraditional(String url, Map params, Map headers, Class clazz) {
HttpHeaders httpHeaders = new HttpHeaders();
params = params == null ? new LinkedHashMap<>() : params;
if (headers != null) {
headers.forEach((o1, o2) -> httpHeaders.add(o1, o2));
}
StringBuilder sb = new StringBuilder(url);
sb.append("?");
params.forEach((o1, o2) -> sb.append(o1).append("=").append(o2).append("&"));
url = sb.toString().replaceAll("&$+|\\?$+", "");
ResponseEntity exchange = restTemplate.exchange(url, HttpMethod.GET, new HttpEntity(null, httpHeaders), clazz);
return exchange.getBody();
}
/**
* GET请求-分隔符参数
*
* @param url
* @param params LinkedHashMap
* @param headers
* @return
*/
public T httpGetPlaceholder(String url, List params, Map headers, Class clazz) {
HttpHeaders httpHeaders = new HttpHeaders();
params = params == null ? new ArrayList<>() : params;
if (headers != null) {
headers.forEach((o1, o2) -> httpHeaders.add(o1, o2));
}
StringBuilder sb = new StringBuilder(url);
params.forEach(o2 -> sb.append("/").append(o2));
url = sb.toString().replaceAll("&$+|\\?$+", "");
ResponseEntity exchange = restTemplate.exchange(url, HttpMethod.GET, new HttpEntity(null, httpHeaders), clazz);
return exchange.getBody();
}
/**
* DELETE请求-?号参数
*
* @param url
* @param params
* @param headers
* @return
*/
public T httpDeleteTraditional(String url, Map params, Map headers, Class clazz) {
HttpHeaders httpHeaders = new HttpHeaders();
params = params == null ? new LinkedHashMap<>() : params;
if (headers != null) {
headers.forEach((o1, o2) -> httpHeaders.add(o1, o2));
}
StringBuilder sb = new StringBuilder(url);
sb.append("?");
params.forEach((o1, o2) -> sb.append(o1).append("=").append(o2).append("&"));
url = sb.toString().replaceAll("&$+|\\?$+", "");
ResponseEntity exchange = restTemplate.exchange(url, HttpMethod.DELETE, new HttpEntity(null, httpHeaders), clazz);
return exchange.getBody();
}
/**
* DELETE请求-分隔符参数
*
* @param url
* @param params
* @param headers
* @return
*/
public T httpDeletePlaceholder(String url, List params, Map headers, Class clazz) {
HttpHeaders httpHeaders = new HttpHeaders();
params = params == null ? new ArrayList<>() : params;
if (headers != null) {
headers.forEach((o1, o2) -> httpHeaders.add(o1, o2));
}
StringBuilder sb = new StringBuilder(url);
params.forEach(o2 -> sb.append("/").append(o2));
url = sb.toString().replaceAll("&$+|\\?$+", "");
ResponseEntity exchange = restTemplate.exchange(url, HttpMethod.DELETE, new HttpEntity(null, httpHeaders), clazz);
return exchange.getBody();
}
}
- 使用
/**
* @author Colin.Ye
* @version 1.0
* @ClassName LowCreateIndexDemo
* @date 2019/3/13
**/
@RestController
@RequestMapping("/lowClient/v1/")
@CrossOrigin
@DefaultProperties(defaultFallback = "defaultFallback")
public class LowCreateIndexDemo extends BaseController {
@Autowired
private RestTemplateUtils restTemplateUtils;
@RequestMapping("/index")
@Log
@HystrixCommand(commandProperties = @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "2000"))
public String index() {
Map params = new HashMap<>();
// 上传文件
FileSystemResource resource = new FileSystemResource(new File("/Users/yezhuang/Documents/data/oracle命令的副本.txt"));
params.put("deviceId", "123424");
params.put("file", resource);
Object o = restTemplateUtils.httpPostFrom("http://localhost:10005/lowClient/v1/test", params, null, String.class);
return o.toString();
}
@RequestMapping("/test")
public String remoteUpdteTest(String deviceId, @RequestParam MultipartFile file) {
System.out.println(deviceId);
System.out.println(file.getName());
return "success";
}
private String fallback() {
return "网络开小差了,请稍后重试···";
}
private String defaultFallback() {
return "defaultFallback: 网络开小差了,请稍后重试···";
}
}