首先注入RestOperations
@Resource
private RestOperations restTemplate;
配置选项
@Configuration
@PropertySource({ "classpath:application.properties" })
public class RestClientConfig {
@Bean
public RestOperations restOperations(ClientHttpRequestFactory clientHttpRequestFactory) throws Exception {
return new RestTemplate(clientHttpRequestFactory);
}
@Bean
public ClientHttpRequestFactory clientHttpRequestFactory(HttpClient httpClient) {
return new HttpComponentsClientHttpRequestFactory(httpClient);
}
@Bean
public HttpClient httpClient(@Value("${keystore.pass}") String password) throws Exception {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
URL url = this.getClass().getClassLoader().getResource("jssecacerts.keystore");
FileInputStream instream = new FileInputStream(new File(url.getPath()));
try {
System.setProperty("javax.net.ssl.trustStore",url.getPath());
trustStore.load(instream, password.toCharArray());
} finally {
instream.close();
}
SSLContext sslcontext =
SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
SSLConnectionSocketFactory sslsf =
new SSLConnectionSocketFactory(sslcontext,new String[]{"SSL","TLS","SSLv2"}, null,
ALLOW_ALL_HOSTNAME_VERIFIER);
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
}
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
传输数据
HttpHeaders headers =new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("clientId",rabbitMQConfig.getClientId());
//json串
ObjectMapper objectMapper=new ObjectMapper();
Map<String,Object> jsonMap= Collections.synchronizedMap(new HashMap<String,Object>());
//得到传输的数据
封装
String jsonParam = "["+objectMapper.writeValueAsString(jsonMap)+"]";
HttpEntity request=new HttpEntity(jsonParam, headers);
//发post请求,以及对结果处理
final String resultValue = restTemplate.postForObject(rabbitMQConfig.getTargerUrl(),request,String.class);