MrShi
5 天以前 3b759ef71bb48f9bb6f8445770d20e8ea7921788
server/jiandaoyun_service/src/main/java/com/doumee/core/jiandaoyun/model/http/ApiClient.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,214 @@
package com.doumee.core.jiandaoyun.model.http;
import com.alibaba.fastjson.JSONObject;
import com.doumee.core.jiandaoyun.util.LimitUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.Charsets;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.io.EmptyInputStream;
import org.apache.http.message.BasicHeader;
import org.apache.http.ssl.SSLContextBuilder;
import javax.net.ssl.SSLContext;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
public abstract class ApiClient {
    /**
     * apiKey
     */
    private String apiKey;
    /**
     * åœ°å€
     */
    private String host;
    /**
     * é»˜è®¤ç‰ˆæœ¬
     */
    private String defaultVersion;
    /**
     * åˆæ³•版本
     */
    private List<String> validVersionList;
    public ApiClient(String apiKey, String host) {
        this.apiKey = apiKey;
        this.host = host;
    }
    public String getApiKey() {
        return apiKey;
    }
    public void setApiKey(String apiKey) {
        this.apiKey = apiKey;
    }
    public String getHost() {
        return host;
    }
    public void setHost(String host) {
        this.host = host;
    }
    public String getDefaultVersion() {
        return defaultVersion;
    }
    public void setDefaultVersion(String defaultVersion) {
        this.defaultVersion = defaultVersion;
    }
    public List<String> getValidVersionList() {
        return validVersionList;
    }
    public void setValidVersionList(List<String> validVersionList) {
        this.validVersionList = validVersionList;
    }
    /**
     * ç”Ÿæˆ path
     *
     * @param version - ç‰ˆæœ¬å·
     * @param path    - è·¯å¾„
     * @return æŽ¥å£çš„路径
     */
    public abstract String generatePath(String version, String path);
    /**
     * èŽ·å¾—åˆæ³•çš„ç‰ˆæœ¬å·
     *
     * @param version - ç‰ˆæœ¬å·
     * @return åˆæ³•的版本号
     */
    public String getValidVersion(String version) {
        if (this.getValidVersionList() != null && this.getValidVersionList().contains(version)) {
            return version;
        }
        return this.getDefaultVersion();
    }
    /**
     * å‘送POST请求
     *
     * @param param - è¯·æ±‚参数
     * @return æŽ¥å£è¿”回参数
     */
    public Map<String, Object> sendPostRequest(HttpRequestParam param) throws Exception {
        if (param == null || StringUtils.isBlank(param.getPath())) {
            throw new Exception("缺失参数!");
        }
        HttpClient client = getSSLHttpClient();
        Header[] headers = getHttpHeaders(this.getApiKey());
        String url = this.host + param.getPath();
        log.error("===简道云接口url:"+url);
        HttpRequestBase request = new HttpPost(url);
        // è¯·æ±‚参数
        if (param.getData() != null) {
            ObjectMapper queryMap = new ObjectMapper();
            HttpEntity entity = new StringEntity(queryMap.writeValueAsString(param.getData()), Charsets.UTF_8);
            ((HttpPost) request).setEntity(entity);
        }
        // è®¾ç½®è¯·æ±‚头
        request.setHeaders(headers);
        // é™æµé˜»å¡ž
        LimitUtil.tryBeforeRun();
        // å‘送请求并获取返回结果
        HttpResponse response = client.execute(request);
        // è¿”回状态码
        int statusCode = response.getStatusLine().getStatusCode();
        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> result = new HashMap<>();
        // æœ‰éƒ¨åˆ†æŽ¥å£ç›´æŽ¥è¿”回 æ²¡æœ‰æ•°æ®
        // fix:不能用content-length大于0判断,response header为gzip编码方式的情况下为-1
        if (!(response.getEntity().getContent() instanceof EmptyInputStream)) {
            result = (Map<String, Object>) mapper.readValue(response.getEntity().getContent(), Object.class);
        }
        if (statusCode >= 400) {
            log.error("===简道云接口:请求错误,statusCode:" + statusCode + ",Error Code: " + result.get("code") + ", Error Msg: " + result.get("msg"));
            throw new Exception("请求错误,statusCode:" + statusCode + ",Error Code: " + result.get("code") + ", Error Msg: " + result.get("msg"));
        } else {
            // å¤„理返回结果
            log.error("===简道云接口:请求成功result:" + JSONObject.toJSONString(result));
            return result;
        }
    }
    private static HttpClient getSSLHttpClient() throws Exception {
        //信任所有
        SSLContext sslContext =
                new SSLContextBuilder().loadTrustMaterial(null, (chain, authType) -> true).build();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
        return HttpClients.custom().setSSLSocketFactory(sslsf).build();
    }
    /**
     * èŽ·å–è¯·æ±‚å¤´ä¿¡æ¯
     *
     * @return è¯·æ±‚头信息
     */
    private Header[] getHttpHeaders(String apiKey) {
        List<Header> headerList = new ArrayList<>();
        headerList.add(new BasicHeader("Authorization", "Bearer " + apiKey));
        headerList.add(new BasicHeader("Content-Type", "application/json;charset=utf-8"));
        return headerList.toArray(new Header[headerList.size()]);
    }
    public Map<String, Object> httpPostFile(String url, String token, File file) throws Exception {
        HttpClient client = getSSLHttpClient();
        HttpPost httpPost = new HttpPost(url);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        httpPost.addHeader("token", token);
        builder.addBinaryBody("file", file, ContentType.MULTIPART_FORM_DATA, file.getName());
        // ä¼ é€’ token
        builder.addTextBody("token", token);
        StringBody tokenBody = new StringBody(token, ContentType.MULTIPART_FORM_DATA);
        builder.addPart("token", tokenBody);
        HttpEntity entity = builder.build();
        httpPost.setEntity(entity);
        // é™æµé˜»å¡ž
        LimitUtil.tryBeforeRun();
        // å‘送请求并获取返回结果
        HttpResponse response = client.execute(httpPost);
        // è¿”回状态码
        int statusCode = response.getStatusLine().getStatusCode();
        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> result = new HashMap<>();
        // æœ‰éƒ¨åˆ†æŽ¥å£ç›´æŽ¥è¿”回 æ²¡æœ‰æ•°æ®
        // fix:不能用content-length大于0判断,response header为gzip编码方式的情况下为-1
        if (!(response.getEntity().getContent() instanceof EmptyInputStream)) {
            result = (Map<String, Object>) mapper.readValue(response.getEntity().getContent(), Object.class);
        }
        if (statusCode >= 400) {
            throw new RuntimeException("请求错误,statusCode:" + statusCode + ",Error Code: " + result.get("code") + ", Error Msg: " + result.get("msg"));
        } else {
            // å¤„理返回结果
            return result;
        }
    }
}