客户端想通过http就访问https的接口,可以配置restample跳过证书校验。注意,这种方式不安全,只能用在测试环境。

1.maven依赖

       <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.14</version>
        </dependency>

2. resTemplate 配置


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.NoopHostnameVerifier;

/**
 * RestTemplate配置
 */
@Configuration
public class RestConfig {

    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
        return new RestTemplate(factory);
    }


    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
        try {
            // 创建SSLContext
            SSLContextBuilder builder = new SSLContextBuilder();
            builder.loadTrustMaterial(null, (certificate, authType) -> true);

            // 设置HttpClientBuilder以使用SSL
            HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
            httpClientBuilder.setSslcontext(builder.build());
            httpClientBuilder.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE);

            // 创建HttpComponentsClientHttpRequestFactory
            HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
            requestFactory.setHttpClient(httpClientBuilder.build());
            return requestFactory;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

3.

@Slf4j
@Configuration
public class RestComponment {
    @Autowired
    RestTemplate restTemplate;

    @Autowired
    FreemarkerComponent freemarkerComponent;


    public String getByNameOrCertCode(String compNameOrCertCode) {
        HttpHeaders requestHeaders = new HttpHeaders();
        HttpEntity httpEntity = new HttpEntity(requestHeaders);
        HttpEntity<String> response = restTemplate.exchange(
                "https://www.hello.com/nsearch?key={companyName}",
                HttpMethod.GET,
                httpEntity,
                String.class,
                compNameOrCertCode
        );
        Document document = Jsoup.parse(response.getBody());
        Elements scriptsElements = document.select("script");

       

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部