欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

springmvc中restTemplate发送https请求

程序员文章站 2022-06-25 20:17:01
...
public static void main(String[] args) {
		String result = "";
		try{
			//rest忽略证书访问
		    HttpComponentsClientHttpRequestFactory factory = new                                                    
		            HttpComponentsClientHttpRequestFactory();
		        factory.setConnectionRequestTimeout(1000);
		        factory.setConnectTimeout(1000);
		        factory.setReadTimeout(1000);
		        // https
		        SSLContextBuilder builder = new SSLContextBuilder();
		        builder.loadTrustMaterial(null, (X509Certificate[] x509Certificates, String s) -> true);
		        SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(builder.build(), new String[]{"SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.2"}, null, NoopHostnameVerifier.INSTANCE);
		        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
		                .register("http", new PlainConnectionSocketFactory())
		                .register("https", socketFactory).build();
		        PoolingHttpClientConnectionManager phccm = new PoolingHttpClientConnectionManager(registry);
		        phccm.setMaxTotal(200);
		        CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).setConnectionManager(phccm).setConnectionManagerShared(true).build();
		        factory.setHttpClient(httpClient);
			//使用RestTemplate进行服务调用,如果非springMVC可以使用httpclient或者httpURLconnection
			RestTemplate restTemplate = new RestTemplate(factory);
			//url建议不要直接写到代码中
			String url ="https://xxx.xxxx.com/api/lapp/token/get";			
			//构造要发送的body体
			//头部
			HttpHeaders headers = new HttpHeaders();
			headers.set("sjly", "A");
			headers.set("yhbs", "4631");
			headers.set("kstime", "201909");
			headers.set("channel", "0");
			//post参数
			MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
			map.add("appKey", "xxxxxxxxxxxxxb50bb");
			map.add("appSecret", "xxxxxxxxxx1243d45b85b33ff2");
			org.springframework.http.HttpEntity<Object> httpEntity = new org.springframework.http.HttpEntity<Object>(map,headers);
			//执行请求获得结果
			result = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class,map).getBody();
			System.out.println("-----------:"+result);
			
		}catch (Exception e) {
			e.printStackTrace();
		}
	}