springmvc中restTemplate发送https请求

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();
		}
	}

猜你喜欢

转载自blog.csdn.net/myfmyfmyfmyf/article/details/101292342
今日推荐