盗代码

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

1、添加HttpClient配置类

package ai.yunji.oa.config;

import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
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.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;
import java.util.List;


@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate(httpRequestFactory());
        List<HttpMessageConverter<?>> httpMessageConverters = restTemplate.getMessageConverters();
        httpMessageConverters.stream().forEach(httpMessageConverter -> {
            if (httpMessageConverter instanceof StringHttpMessageConverter) {
                StringHttpMessageConverter messageConverter = (StringHttpMessageConverter) httpMessageConverter;
                messageConverter.setDefaultCharset(Charset.forName("UTF-8"));
            }
        });
        return restTemplate ;
    }



    /**
     * @return
     */
    @Bean
    public ClientHttpRequestFactory httpRequestFactory() {
        return new HttpComponentsClientHttpRequestFactory(httpClient());
    }

    
    @Bean
    public HttpClient httpClient() {
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", SSLConnectionSocketFactory.getSocketFactory())
                .build();
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
        //设置整个连接池最大连接数 根据自己的场景决定
        connectionManager.setMaxTotal(200);
        //路由是对maxTotal的细分
        connectionManager.setDefaultMaxPerRoute(100);
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(10000) //服务器返回数据(response)的时间,超过该时间抛出read timeout
                .setConnectTimeout(5000)//连接上服务器(握手成功)的时间,超出该时间抛出connect timeout
                .setConnectionRequestTimeout(5000)//从连接池中获取连接的超时时间,超过该时间未拿到可用连接,会抛出org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection from pool
                .build();

        return HttpClientBuilder.create()
                .setDefaultRequestConfig(requestConfig)
                .setConnectionManager(connectionManager)
                .build();
    }
}

2、封装通用方法

package ai.yunji.oa.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.shaded.com.google.gson.JsonObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@Service
@Configuration
public class HttpConfig {

    @Autowired
    RestTemplate restTemplate;

    @Value("${crm.url}")
    private String beforeUrl;

    public JSONObject httpPost(Object object,String crmToken,String afterUrl){
        JSONObject params = new JSONObject();
        params.put("data",object);
        HttpHeaders headers = new HttpHeaders();
        headers.add("contentType", "application/json");
        headers.add("Authorization", crmToken);
        HttpEntity<JSONObject> requestEntity = new HttpEntity<JSONObject>(params,headers);

        // 获取响应信息,包含响应状态、响应头、响应内容
        ResponseEntity<String> entity = restTemplate.exchange(beforeUrl+afterUrl , HttpMethod.POST, requestEntity, String.class);
        JSONObject data = JSON.parseObject(entity.getBody());
        if (data.get("code").equals("200")){
            JSONObject crm = data.getJSONObject("data");
            return crm;
        }
        return data;
    }

    public JSONObject httpGet(String params,String crmToken,String afterUrl){
        HttpHeaders headers = new HttpHeaders();
        headers.add("contentType", "application/json");
        headers.add("Authorization", crmToken);
        HttpEntity<JSONObject> requestEntity = new HttpEntity<JSONObject>(headers);

        // 获取响应信息,包含响应状态、响应头、响应内容
        ResponseEntity<String> entity = restTemplate.exchange(beforeUrl+afterUrl+"?"+params , HttpMethod.GET, requestEntity, String.class);
        JSONObject data = JSON.parseObject(entity.getBody());
        if (data.get("code").equals("200")){
            JSONObject crm = data.getJSONObject("data");
            return crm;
        }
        return data;
    }

}

3、调用方式

Map<String, String> params = new HashMap<String, String>();
JSONObject data = httpConfig.httpPost(参数, "token值", "地址值");     

 

posted on 2021-08-12 14:57    阅读(234)  评论(0)    收藏  举报