springboot中基于RestTemplate 类 实现调用第三方API接口【java】

2023-12-21 01:03:08
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
 /**
     * 调用第三方服务器接口  附件上传的那种
     * 传入JSONObject表示post请求
     * 不传表示get请求
     * @param url 路由
     * @param jsonObject 参数
     * @param method 方法
     * @return
     */
    public static JSONObject forwardAlgorithm(String url, MultiValueMap<String, Object> jsonObject, HttpMethod method, List<String> stringList) throws Exception{
        RestTemplate restTemplate = new RestTemplate(RestTemplateConfig.generateHttpRequestFactory());
        //此处加编码格式转换
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        HttpHeaders httpHeaders = new HttpHeaders();

        httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
        //   httpHeaders.setContentType(org.springframework.http.MediaType.APPLICATION_JSON_UTF8);
        //    httpHeaders.put("Authorization",stringList);
        HttpEntity httpEntity = new HttpEntity(jsonObject, httpHeaders);
        //访问第三方服务器
        ResponseEntity<String> exchange = restTemplate.exchange(url, method, httpEntity, String.class);
        return JSONObject.parseObject(exchange.getBody(),JSONObject.class);
    }

  /**
     * 调用第三方服务器接口  没有附件上传的那种
     * 传入JSONObject表示post请求
     * 不传表示get请求
     * @param url 路由
     * @param jsonObject 参数
     * @param method 方法
     * @return
     */
    public  JSONObject forwardAlgorithm(String url, JSONObject jsonObject, HttpMethod method, List<String> stringList) throws Exception{
        RestTemplate restTemplate = new RestTemplate(RestTemplateConfig.generateHttpRequestFactory());
        //此处加编码格式转换
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(org.springframework.http.MediaType.APPLICATION_JSON_UTF8);
        httpHeaders.put("Authorization",stringList);
        HttpEntity httpEntity = new HttpEntity(jsonObject, httpHeaders);
        //访问第三方服务器
        ResponseEntity<String> exchange = restTemplate.exchange(url, method, httpEntity, String.class);
        return JSONObject.parseObject(exchange.getBody(),JSONObject.class);
    }

RestTemplateConfig配置文件

package com.erp.yt.common.init.config;

import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.ssl.TrustStrategy;
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 javax.net.ssl.SSLContext;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;

/**
 *  restTemplate配置类
 *
 * @author Json
 */

@Configuration
public class RestTemplateConfig {

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

    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        factory.setConnectTimeout(15000);
        factory.setReadTimeout(5000);
        return factory;
    }

    public static HttpComponentsClientHttpRequestFactory generateHttpRequestFactory()
            throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException
    {
        TrustStrategy acceptingTrustStrategy = (x509Certificates, authType) -> true;
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
        SSLConnectionSocketFactory connectionSocketFactory = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());

        HttpClientBuilder httpClientBuilder = HttpClients.custom();
        httpClientBuilder.setSSLSocketFactory(connectionSocketFactory);
        CloseableHttpClient httpClient = httpClientBuilder.build();
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        factory.setHttpClient(httpClient);
        return factory;
    }
}

调用举例

        FileSystemResource resource = new FileSystemResource(pathNameList.get(0));
        FileSystemResource resource1 = new FileSystemResource(pathNameList.get(1));
        FileSystemResource resource3 = new FileSystemResource(pathNameList.get(2));
        MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<>();
        List<FileSystemResource> resourceList=new ArrayList<>();
        resourceList.add(resource);
        resourceList.add(resource1);
        resourceList.add(resource3);
        paramMap.add("myfiles", resourceList);
        paramMap.add("accessToken", accessToken);
        paramMap.add("groupId", groupId);



        //  JSONObject jsonData = (JSONObject) JSON.toJSON(data);
        String url="";

        List<String> stringList=new ArrayList<>();


        JSONObject s =test.forwardAlgorithm(url, paramMap,HttpMethod.POST,stringList);

忽略证书验证 更详细请参考下面博客
https://blog.csdn.net/Drug_/article/details/129191580

文章来源:https://blog.csdn.net/Drug_/article/details/135111675
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。