Spring/SpringBoot内置Http请求工具RestTemplate介绍和使用

2022-10-02 71点热度 0人点赞 0条评论

在开发中有时候经常需要一些Http请求,请求数据,下载内容,也有一些简单的分布式应用直接使用Http请求作为跨应用的交互协议。

在Java中有不同的Http请求方式,主要就是HttpURLConnection或者ApacheHttpClient,另外还有比较注明的OKHttp,或者国内常用的Hutool;

Spring也内置了RestTemplate作为Http请求的工具类,简化了很多操作,虽然Spring5推出了WebClient,但是整体感觉还是RestTemplate用起来更简单方便一些。

这里记录分享下RestTemplate的常见使用方式,RestTemplate作为Java中最简单好用的Http请求工具类一定要了解一下

常见用法

简单Get/Post请求

RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new FastJsonHttpMessageConverter());
String res = restTemplate.postForObject("https://httpbin.org/post", null, String.class);
System.out.println(res);
String res2 = restTemplate.getForObject("https://httpbin.org/get",  String.class);
System.out.println(res2);

 

Post提交常规表单

RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
map.add("id", "1");
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);

String fooResourceUrl = "https://httpbin.org/post";
ResponseEntity<String> response = restTemplate.postForEntity(fooResourceUrl, request, String.class);
System.out.println(response.getStatusCode());
System.out.println(response.getBody());

 

Post上传文件

注意:上传文件时的value为FileSystemResource

RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
MultiValueMap<String, Object> map= new LinkedMultiValueMap<>();
map.add("id", "1");
map.add("file",new FileSystemResource("/path/to/example.jpg"));
HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(map, headers);
String fooResourceUrl = "https://httpbin.org/post";
ResponseEntity<String> response = restTemplate.postForEntity(fooResourceUrl, request, String.class);
System.out.println(response.getStatusCode());
System.out.println(response.getBody());

 

配置项

请求添加Cookie\Header

RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
MultiValueMap<String, Object> map= new LinkedMultiValueMap<>();

// 常见的Header都可以直接设置
//        headers.set
headers.set("custom1","customValue1");

// 设置Cookie
headers.set(HttpHeaders.COOKIE,"xxxx");

map.add("id", "1");
HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(map, headers);
String fooResourceUrl = "https://httpbin.org/post";
ResponseEntity<String> response = restTemplate.postForEntity(fooResourceUrl, request, String.class);
System.out.println(response.getStatusCode());
System.out.println(response.getBody());

 

配置请求工厂 超时、代理

使用Rest请求的时候注意设置超时时间

RestTemplate restTemplate = new RestTemplate();
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setReadTimeout(5000);
requestFactory.setConnectTimeout(3000);

Proxy proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("127.0.0.1", 1080));

requestFactory.setProxy(proxy);
restTemplate.setRequestFactory(requestFactory);

restTemplate.getMessageConverters().add(new FastJsonHttpMessageConverter());
String res = restTemplate.postForObject("https://httpbin.org/post", null, String.class);
System.out.println(res);

 

配置拦截器、转换器,错误处理

RestTemplate restTemplate = new RestTemplate();
restTemplate.setInterceptors(Collections.singletonList(new BasicAuthenticationInterceptor("admin","admin")));
restTemplate.getMessageConverters().add(new FastJsonHttpMessageConverter());
restTemplate.setErrorHandler(new DefaultResponseErrorHandler());
String res = restTemplate.postForObject("https://httpbin.org/post", null, String.class);
System.out.println(res);

 

错误重试(额外)

可以考虑使用Spring Retry,但是相当于引入了新的东西,如果没有特殊必要,可以自己简单用for循环做下;

// Spring Retry方式
@Bean
public RetryTemplate retryTemplate() {
    int maxAttempt = Integer.parseInt(env.getProperty("maxAttempt"));
    int retryTimeInterval = Integer.parseInt(env.getProperty("retryTimeInterval"));

    SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
    retryPolicy.setMaxAttempts(maxAttempt);

    FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
      // 失败的间隔
    backOffPolicy.setBackOffPeriod(retryTimeInterval); 

    RetryTemplate template = new RetryTemplate();
    template.setRetryPolicy(retryPolicy);
    template.setBackOffPolicy(backOffPolicy);

    return template;
}

 

SSL请求

String keyStorePassword = "123456";
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(new FileInputStream(new File("keyStoreFile")),
        keyStorePassword.toCharArray());

SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
        new SSLContextBuilder()
                .loadTrustMaterial(null, new TrustSelfSignedStrategy())
                .loadKeyMaterial(keyStore, keyStorePassword.toCharArray())
                .build(),
        NoopHostnameVerifier.INSTANCE);

HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(
        socketFactory).build();

ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(
        httpClient);
RestTemplate restTemplate = new RestTemplate(requestFactory);
String res = restTemplate.postForObject("https://httpbin.org/post", null, String.class);
System.out.println(res);

 

总结

1、 Http请求在开发过程中也是一个常见的高频操作;

2、Spring封装了Http的工具类RestTemplate非常好用,基本上满足了所有Http相关的需求。

3、这里介绍整理了下RestTemplate的常见使用方式,遇到有对应的内容,直接翻阅使用即可。

admin

这个人很懒,什么都没留下

文章评论

您需要 登录 之后才可以评论