网络请求模板(RestTemplate)

对于返回格式为JSON的资源或者 Restful 接口,统一采用RestTemplate来请求,其它类型响应数据的也建议采用不同的MessageConverter来实现, 建议再延续使用自定义的类似HttpUtilsHttpHelper之类的工具类。

RestTemplate 的统一配置

根据业务场景的实际需要,全局统一配置RestTemplate,示例代码如下:

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
@Configuration
public class RestTemplateConfiguration {

@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
RestTemplate restTemplate = new RestTemplate(factory);
restTemplate.getMessageConverters().add(new PlainTextJackson2HttpMessageConverter());
return restTemplate;
}

@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setReadTimeout(5000);
factory.setConnectTimeout(10000);
return factory;
}

/**
* 支持普通文本的转换器
*/
public static class PlainTextJackson2HttpMessageConverter extends MappingJackson2HttpMessageConverter {
PlainTextJackson2HttpMessageConverter() {
List<MediaType> mediaTypes = new ArrayList<>();
mediaTypes.add(MediaType.TEXT_PLAIN);
mediaTypes.add(MediaType.TEXT_HTML);
mediaTypes.add(MediaType.APPLICATION_OCTET_STREAM);
setSupportedMediaTypes(mediaTypes);
}
}
}

使用方式

  • 简单场景:返回普通的 String

    1
    2
    3
    4
    5
    6
    7
    8
    9
    UriComponents uriComponents = UriComponentsBuilder.fromUriString(config.getVmsServerGateway())
    .queryParam("fromUserCode", config.getVmsFromUserCode())
    .queryParam("toUserCode", account)
    .queryParam("msgText", content)
    .queryParam("key", DigestUtils.md5Hex(config.getVmsFromUserCode() + account + config.getVmsKey())).build();
    log.info("URL:{}", uriComponents.toUriString());

    // Get 方法
    String result = restTemplate.getForObject(uriComponents.toUriString(), String.class);
  • 格式化数据场景

    1
    2
    3
    HttpEntity<MultiValueMap<String, Object>> entities = new HttpEntity<>(new HttpHeaders());
    ApiResult<SearchResult> result = restTemplate.exchange(uriComponents.toUriString(), HttpMethod.POST, entities,
    new ParameterizedTypeReference<ApiResult<SearchResult>>() {}).getBody();

    注:序列化方式依赖系统中配置的MessageConverter