Springboot-使用RestTemplate方式发HTTP请求及上传文件

RestTemplate是Spring提供的用于访问Rest服务的客户端,RestTemplate提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率。

我基于RestTemplate编写了一个工具类,方便使用。工具类提供之提供了GET、POST、DELETE请求方法,其他方法自行补充


  1. Application启动类中实例RestTemplate

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    @SpringBootApplication
    @RestController
    public class Applicatiohexn {
    public static void main(String[] args) {
    SpringApplication.run(ElasticApplication.class, args);
    }
    @Bean
    public RestTemplate restTemplate() {
    // new HttpComponentsClientHttpRequestFactory()作用:支持patch请求
    RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
    // restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
    return restTemplate;
    }
    }
  2. RestTemplateUtils工具类 点击下载

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    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> T httpPostJson(String url, Map params, Map headers, Class<T> clazz) {
    HttpHeaders httpHeaders = new HttpHeaders();
    if (headers != null) {
    headers.forEach((o1, o2) -> httpHeaders.add(o1.toString(), o2.toString()));
    }
    // json方式传参
    return restTemplate.postForObject(url, new HttpEntity(params, httpHeaders), clazz);
    }

    /**
    * POST请求-FROM参数
    *
    * @param url
    * @param params
    * @param headers
    * @return
    */
    public <T> T httpPostForm(String url, Map params, Map headers, Class<T> clazz) {
    HttpHeaders httpHeaders = new HttpHeaders();
    params = params == null ? new LinkedHashMap<>() : params;
    if (headers != null) {
    headers.forEach((o1, o2) -> httpHeaders.add(o1.toString(), o2.toString()));
    }
    MultiValueMap<String, Object> stringObjectLinkedMultiValueMap = new LinkedMultiValueMap<>();
    params.forEach((o1, o2) -> stringObjectLinkedMultiValueMap.add(o1.toString(), o2));
    // 表单方式传参
    // json方式传参
    return restTemplate.postForObject(url, new HttpEntity(stringObjectLinkedMultiValueMap, httpHeaders), clazz);
    }

    /**
    * GET请求-?号参数
    *
    * @param url
    * @param params
    * @param headers
    * @return
    */
    public <T> T httpGetTraditional(String url, Map params, Map headers, Class<T> clazz) {
    HttpHeaders httpHeaders = new HttpHeaders();
    params = params == null ? new LinkedHashMap<>() : params;
    if (headers != null) {
    headers.forEach((o1, o2) -> httpHeaders.add(o1.toString(), o2.toString()));
    }
    StringBuilder sb = new StringBuilder(url);
    sb.append("?");
    params.forEach((o1, o2) -> sb.append(o1).append("=").append(o2).append("&"));
    url = sb.toString().replaceAll("&$+|\\?$+", "");
    ResponseEntity<T> exchange = restTemplate.exchange(url, HttpMethod.GET, new HttpEntity(null, httpHeaders), clazz);
    return exchange.getBody();
    }

    /**
    * GET请求-分隔符参数
    *
    * @param url
    * @param params
    * @param headers
    * @return
    */
    public <T> T httpGetPlaceholder(String url, List params, Map headers, Class<T> clazz) {
    HttpHeaders httpHeaders = new HttpHeaders();
    params = params == null ? new ArrayList<>() : params;
    if (headers != null) {
    headers.forEach((o1, o2) -> httpHeaders.add(o1.toString(), o2.toString()));
    }
    StringBuilder sb = new StringBuilder(url);
    params.forEach(o2 -> sb.append("/").append(o2));
    url = sb.toString().replaceAll("&$+|\\?$+", "");
    ResponseEntity<T> exchange = restTemplate.exchange(url, HttpMethod.GET, new HttpEntity(null, httpHeaders), clazz);
    return exchange.getBody();
    }

    /**
    * DELETE请求-?号参数
    *
    * @param url
    * @param params
    * @param headers
    * @return
    */
    public <T> T httpDeleteTraditional(String url, Map params, Map headers, Class<T> clazz) {
    HttpHeaders httpHeaders = new HttpHeaders();
    params = params == null ? new LinkedHashMap<>() : params;
    if (headers != null) {
    headers.forEach((o1, o2) -> httpHeaders.add(o1.toString(), o2.toString()));
    }
    StringBuilder sb = new StringBuilder(url);
    sb.append("?");
    params.forEach((o1, o2) -> sb.append(o1).append("=").append(o2).append("&"));
    url = sb.toString().replaceAll("&$+|\\?$+", "");
    ResponseEntity<T> exchange = restTemplate.exchange(url, HttpMethod.DELETE, new HttpEntity(null, httpHeaders), clazz);
    return exchange.getBody();
    }

    /**
    * DELETE请求-分隔符参数
    *
    * @param url
    * @param params
    * @param headers
    * @return
    */
    public <T> T httpDeletePlaceholder(String url, List params, Map headers, Class<T> clazz) {
    HttpHeaders httpHeaders = new HttpHeaders();
    params = params == null ? new ArrayList<>() : params;
    if (headers != null) {
    headers.forEach((o1, o2) -> httpHeaders.add(o1.toString(), o2.toString()));
    }
    StringBuilder sb = new StringBuilder(url);
    params.forEach(o2 -> sb.append("/").append(o2));
    url = sb.toString().replaceAll("&$+|\\?$+", "");
    ResponseEntity<T> exchange = restTemplate.exchange(url, HttpMethod.DELETE, new HttpEntity(null, httpHeaders), clazz);
    return exchange.getBody();
    }

    /**
    * PATCH请求-JSON参数
    *
    * @param url
    * @param params
    * @param headers
    * @return
    */
    public <T> T httpPatchJson(String url, Map params, Map headers, Class<T> clazz) {
    HttpHeaders httpHeaders = new HttpHeaders();
    if (headers != null) {
    headers.forEach((o1, o2) -> httpHeaders.add(o1.toString(), o2.toString()));
    }
    // json方式传参
    return restTemplate.patchForObject(url, new HttpEntity(params, httpHeaders), clazz);
    }

    /**
    * patch请求-FROM参数
    *
    * @param url
    * @param params
    * @param headers
    * @return
    */
    public <T> T httpPatchForm(String url, Map params, Map headers, Class<T> clazz) {
    HttpHeaders httpHeaders = new HttpHeaders();
    params = params == null ? new LinkedHashMap<>() : params;
    if (headers != null) {
    headers.forEach((o1, o2) -> httpHeaders.add(o1.toString(), o2.toString()));
    }
    MultiValueMap<String, Object> stringObjectLinkedMultiValueMap = new LinkedMultiValueMap<>();
    params.forEach((o1, o2) -> stringObjectLinkedMultiValueMap.add(o1.toString(), o2));
    // 表单方式传参
    // json方式传参
    return restTemplate.patchForObject(url, new HttpEntity(stringObjectLinkedMultiValueMap, httpHeaders), clazz);
    }
    }
  3. 使用

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    /**
    * @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<String, Object> 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: 网络开小差了,请稍后重试···";
    }
    }

相关文章

评论系统未开启,无法评论!