使用RestTemplate调用外部https接口

RestTemplate支持调用Http和Https接口

  • 1.添加 RestTemplateConfig 配置类
package com.txb.project.config;

import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

/**
 1. 获取restTemplate
 2. @author tianxiubiao
 */
@Configuration
public class RestTemplateConfig {


	@Bean
	@LoadBalanced
	public RestTemplate restTemplate(RestTemplateBuilder builder) {
		return builder.build();
	}
}
  1. 添加 HttpsClientRequestFactory
package com.txb.project.util;

import org.springframework.http.client.SimpleClientHttpRequestFactory;

import javax.net.ssl.*;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.Socket;
import java.security.cert.X509Certificate;

/**
 * TLS的三个作用:
 *  (1)身份认证
 *      通过证书认证来确认对方的身份,防止中间人攻击
 *  (2)数据私密性
 *      使用对称性密钥加密传输的数据,由于密钥只有客户端/服务端有,其他人无法窥探。
 *  (3)数据完整性
 *      使用摘要算法对报文进行计算,收到消息后校验该值防止数据被篡改或丢失。
 *
 *     使用RestTemplate进行HTTPS请求访问:
 *  private static RestTemplate restTemplate = new RestTemplate(new HttpsClientRequestFactory());
 *
 * @author tianxiubiao
 */
public class HttpsClientRequestFactory extends SimpleClientHttpRequestFactory {
	@Override
	protected void prepareConnection(HttpURLConnection connection, String httpMethod) {
		try {
			if (!(connection instanceof HttpsURLConnection)) {
				throw new RuntimeException("An instance of HttpsURLConnection is expected");
			}

			HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
			TrustManager[] trustAllCerts = new TrustManager[]{
				new X509TrustManager() {
					@Override
					public java.security.cert.X509Certificate[] getAcceptedIssuers() {
						return null;
					}
					@Override
					public void checkClientTrusted(X509Certificate[] certs, String authType) {
					}
					@Override
					public void checkServerTrusted(X509Certificate[] certs, String authType) {
					}
				}
			};
			SSLContext sslContext = SSLContext.getInstance("TLS");
			sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
			httpsConnection.setSSLSocketFactory(new MyCustomSSLSocketFactory(sslContext.getSocketFactory()));

			httpsConnection.setHostnameVerifier(new HostnameVerifier() {
				@Override
				public boolean verify(String s, SSLSession sslSession) {
					return true;
				}
			});

			super.prepareConnection(httpsConnection, httpMethod);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	private static class MyCustomSSLSocketFactory extends SSLSocketFactory {
		private final SSLSocketFactory delegate;
		public MyCustomSSLSocketFactory(SSLSocketFactory delegate) {
			this.delegate = delegate;
		}

		// 返回默认启用的密码套件。除非一个列表启用,对SSL连接的握手会使用这些密码套件。
		// 这些默认的服务的最低质量要求保密保护和服务器身份验证
		@Override
		public String[] getDefaultCipherSuites() {
			return delegate.getDefaultCipherSuites();
		}

		// 返回的密码套件可用于SSL连接启用的名字
		@Override
		public String[] getSupportedCipherSuites() {
			return delegate.getSupportedCipherSuites();
		}

		@Override
		public Socket createSocket(final Socket socket, final String host, final int port,
								   final boolean autoClose) throws IOException {
			final Socket underlyingSocket = delegate.createSocket(socket, host, port, autoClose);
			return overrideProtocol(underlyingSocket);
		}

		@Override
		public Socket createSocket(final String host, final int port) throws IOException {
			final Socket underlyingSocket = delegate.createSocket(host, port);
			return overrideProtocol(underlyingSocket);
		}

		@Override
		public Socket createSocket(final String host, final int port, final InetAddress localAddress,
								   final int localPort) throws
			IOException {
			final Socket underlyingSocket = delegate.createSocket(host, port, localAddress, localPort);
			return overrideProtocol(underlyingSocket);
		}

		@Override
		public Socket createSocket(final InetAddress host, final int port) throws IOException {
			final Socket underlyingSocket = delegate.createSocket(host, port);
			return overrideProtocol(underlyingSocket);
		}

		@Override
		public Socket createSocket(final InetAddress host, final int port, final InetAddress localAddress,
								   final int localPort) throws
			IOException {
			final Socket underlyingSocket = delegate.createSocket(host, port, localAddress, localPort);
			return overrideProtocol(underlyingSocket);
		}

		private Socket overrideProtocol(final Socket socket) {
			if (!(socket instanceof SSLSocket)) {
				throw new RuntimeException("An instance of SSLSocket is expected");
			}
			//((SSLSocket) socket).setEnabledProtocols(new String[]{"TLSv1.2"});
			((SSLSocket) socket).setEnabledProtocols(new String[]{"TLSv1", "TLSv1.1", "TLSv1.2"});
			return socket;
		}
	}
}

  1. 调用过程中通过判断url传递不同参数创建RestTemplate对象

	//如果不是https接口使用默认注入的
	//@Autowired
	//private RestTemplate restTemplate;
	if (((String) map.get("url")).contains("https:")){
			restTemplate = new RestTemplate(new HttpsClientRequestFactory());
	}
	
	//设置请求头
	HttpHeaders headers = new HttpHeaders();
	Map<String,String> headerMap = (Map<String, String>) map.get("headerMap");
	if (headerMap != null && headerMap.size() > 0){
		for (Map.Entry<String, String> header : headerMap.entrySet()) {
			headers.add(header.getKey(),header.getValue());
		}
	}

	//调用接口返回data
	ResponseEntity<Object> responseEntity = restTemplate.exchange((String) map.get("url"), HttpMethod.GET, request, Object.class);
	return R.data(responseEntity.getBody());

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
SpringBoot可以使用RestTemplate调用外部的webservice接口。首先,你需要在SpringBoot中整合RestTemplate。你可以创建一个配置类,使用@Configuration注解标记,并注入RestTemplate bean。在配置类中,你可以设置RestTemplate的一些属性,比如连接超时时间、读取超时时间等。然后,你可以使用RestTemplate的方法来发送HTTP请求,调用外部的webservice接口。你可以使用getForObject或postForObject等方法来发送GET或POST请求,并获取返回的结果。在调用webservice接口时,你需要提供接口的URL、请求参数等信息。你可以使用RestTemplate的exchange方法来发送请求,并获取返回的ResponseEntity对象,然后从ResponseEntity对象中获取返回的数据。总之,使用RestTemplate可以方便地调用外部的webservice接口。\[1\]如果你觉得使用webservice客户端调用服务器端不方便,或者不会使用webservice客户端,可以尝试使用RestTemplate调用webservice接口。\[1\]在SpringBoot中整合RestTemplate需要引入相应的依赖,比如spring-boot-starter-web-services和cxf-spring-boot-starter-jaxws等。你可以在项目的pom.xml文件中添加这些依赖。\[3\]然后,你可以创建一个配置类,使用@Configuration注解标记,并注入RestTemplate bean。在配置类中,你可以设置RestTemplate的一些属性,比如连接超时时间、读取超时时间等。\[2\]接下来,你可以使用RestTemplate的方法来发送HTTP请求,调用外部的webservice接口。你可以使用getForObject或postForObject等方法来发送GET或POST请求,并获取返回的结果。在调用webservice接口时,你需要提供接口的URL、请求参数等信息。你可以使用RestTemplate的exchange方法来发送请求,并获取返回的ResponseEntity对象,然后从ResponseEntity对象中获取返回的数据。总之,使用RestTemplate可以方便地调用外部的webservice接口。 #### 引用[.reference_title] - *1* [基于Springboot整合RestTemplate调用Webservice接口](https://blog.csdn.net/u011652364/article/details/117544660)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down1,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [SpringBoot2.3整合WebService实现远程调用](https://blog.csdn.net/liu320yj/article/details/121740367)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值