-
-
Save ryenus/edab6098dc4bc5082d13891632f086f3 to your computer and use it in GitHub Desktop.
Spring RestTemplate with Support for Connecting to https with selfsigned Certificates (ApacheHTTPClient >= 4.4) and ByteArrays in Responses
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
import java.util.List; | |
import org.apache.http.conn.ssl.NoopHostnameVerifier; | |
import org.apache.http.impl.client.CloseableHttpClient; | |
import org.apache.http.impl.client.HttpClients; | |
import org.springframework.http.MediaType; | |
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; | |
import org.springframework.http.converter.ByteArrayHttpMessageConverter; | |
import org.springframework.web.client.RestTemplate; | |
public class RestTemplateConfig { | |
public static RestTemplate initRestTemplateForPdfAsByteArrayAndSelfSignedHttps() { | |
RestTemplate restTemplate = new RestTemplate(useApacheHttpClientWithSelfSignedSupport()); | |
restTemplate.getMessageConverters().add(generateByteArrayHttpMessageConverter()); | |
return restTemplate; | |
} | |
private static HttpComponentsClientHttpRequestFactory useApacheHttpClientWithSelfSignedSupport() { | |
CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); | |
HttpComponentsClientHttpRequestFactory useApacheHttpClient = new HttpComponentsClientHttpRequestFactory(); | |
useApacheHttpClient.setHttpClient(httpClient); | |
return useApacheHttpClient; | |
} | |
private static ByteArrayHttpMessageConverter generateByteArrayHttpMessageConverter() { | |
ByteArrayHttpMessageConverter byteArrayHttpMessageConverter = new ByteArrayHttpMessageConverter(); | |
List<MediaType> supportedApplicationTypes = new ArrayList<MediaType>(); | |
supportedApplicationTypes.add(new MediaType("application","pdf")); | |
byteArrayHttpMessageConverter.setSupportedMediaTypes(supportedApplicationTypes); | |
return byteArrayHttpMessageConverter; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment