接口对接代理、HttpUtils工具类

public AjaxResult zhihuiya(@RequestBody ZlRecord zlRecord) {
        //查看用户或者部门有没有下载次数
        SysUser user = SecurityUtils.getLoginUser().getUser();
        ZlCount zlCount = newLabelMapper.selectUserCount(user.getUserId());
        if (ObjectUtils.isEmpty(zlCount)){
            ZlCount zlCount2 = newLabelMapper.selectDeptCount(user.getDeptId());
            if (ObjectUtils.isEmpty(zlCount2))
                throw new RuntimeException("该部门或用户没有下载次数");
        }
        //获取token
        String token="";
        String jobid="";
        String filePath="";
        String patentNumber="CN106561027B";
        String clientId="w6nf8ZI4AKA0oYgjJb";
        String clientSecret="Gy2geNN56TX1h79";
        String cacheObject = redisCache.getCacheObject("zha");
        if (StringUtils.isNotEmpty(cacheObject)){
            token = cacheObject;
        }else {
            String tokenhost = "https://"+clientId+":"+clientSecret+"@connect.ziya.com";
            String tokenpath = "/oauth/token";
            Map headers = new HashMap();
            headers.put("Content-Type", "application/x-www-form-urlencoded");
            Map requestbody = new HashMap();
            requestbody.put("grant_type", "client_credentials");
            try {
                HttpResponse response = HttpUtils.doPost(tokenhost, tokenpath, null, headers, null, requestbody);
                String result = EntityUtils.toString(response.getEntity());
                System.out.println(result);
                org.json.JSONObject jsonResponse = new org.json.JSONObject(result);
                org.json.JSONObject data = jsonResponse.getJSONObject("data");
                if (data.has("token")&&StringUtils.isNotEmpty(data.getString("token"))){
                    token = "Bearer "+data.getString("token");
                    redisCache.setCacheObject("zhihuiya" , token, 25, TimeUnit.MINUTES);
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new ServiceException("获取token失败", HttpStatus.ERROR);
            }
        }


        //获取专利jobid
        String host = "https://connect.zya.com";
        String path = "/patent-valuation-data/patent-report/task/create";

        Map headers2 = new HashMap();
        headers2.put("Content-Type", "application/json");
        headers2.put("authorization", token);

        Map querys = new HashMap();
        querys.put("apikey", clientId);
        //JSONObject dataBody = (JSONObject) JSON.parse("{\"report_type\":\"pdf\",\"patent_number\":\"CN108977442B\"}");

        JSONObject dataBody = new JSONObject();
        dataBody.put("report_type", "pdf");
        dataBody.put("patent_number", zlRecord.getPatentNumber());
        try {
            HttpResponse response = HttpUtils.doPost(host, path, null, headers2, querys, dataBody.toJSONString());
            String result = EntityUtils.toString(response.getEntity());
            System.out.println(result);
            org.json.JSONObject jsonResponse = new org.json.JSONObject(result);
            org.json.JSONObject data = jsonResponse.getJSONObject("data");
            jobid = data.getString("job_id");
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("获取报告导出任务失败", HttpStatus.ERROR);
        }
        //获取导出链接
        String host3 = "https://connect.zhya.com";
        String path3 = "/patent-valuation-data/patent-report/job_id/status";

        Map headers3 = new HashMap();
        headers3.put("Content-Type", "application/json");
        headers3.put("authorization", token);

        Map querys3 = new HashMap();
        querys3.put("job_id", jobid);
        querys3.put("apikey", clientId);
        try {
            HttpResponse response = HttpUtils.doGet(host3, path3, null, headers3, querys3);
            String result = EntityUtils.toString(response.getEntity());
            System.out.println(result);
            org.json.JSONObject jsonResponse = new org.json.JSONObject(result);
            org.json.JSONObject data = jsonResponse.getJSONObject("data");
            if (jsonResponse.has("error_code")&&jsonResponse.getInt("error_code")!=0){
                throw new ServiceException("下载报告失败"+jsonResponse.getInt("error_code"), HttpStatus.ERROR);
            }
            if (data.has("job_status")&&jsonResponse.getInt("error_code")==0){
                while (data.getInt("job_status")==1){
                    System.out.println("导出中");
                    Thread.sleep(5000); // 延迟1秒
                    response = HttpUtils.doGet(host3, path3, null, headers3, querys3);
                    result = EntityUtils.toString(response.getEntity());
                    jsonResponse = new org.json.JSONObject(result);
                    data = jsonResponse.getJSONObject("data");
                }
                if (data.getInt("job_status")==2){
                    System.out.println("导出完成");
                    filePath = data.getString("download_url");
                }else {
                    throw new ServiceException("导出失败"+data.getInt("job_status")+"errorcode"+jsonResponse.getString("error_code"), HttpStatus.ERROR);
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("导出报告失败", HttpStatus.ERROR);
        }
        String fileName1="";
        InetSocketAddress addr = new InetSocketAddress("192.188.3.26", 28083);
        Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);
        try {
            // 创建URL对象指向文件下载地址
            URL url = new URL(filePath);

            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection(proxy );

            // 设置请求方法为GET
            connection.setRequestMethod("GET");

            // 准备读取响应
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                String fileNameWithQuery = filePath.substring(filePath.lastIndexOf("/") + 1);
                int queryIndex = fileNameWithQuery.indexOf("?");
                String fileName = (queryIndex != -1) ? fileNameWithQuery.substring(0, queryIndex) : fileNameWithQuery;

                long currentTimeMillis = System.currentTimeMillis();

                 fileName1 = user.getUserId()+"_"+currentTimeMillis+"_"+fileName;
                // 指定本地保存的路径和文件名
                Path saveFilePath = Paths.get("/home/www/zlbg/", fileName1);

                // 创建文件输出流用于写入文件
                Files.copy(connection.getInputStream(), saveFilePath, StandardCopyOption.REPLACE_EXISTING);

                System.out.println("文件下载成功:" + saveFilePath.toAbsolutePath());
                System.out.println("/home/www/zlbg/"+ fileName1);
                zlRecord.setId(UUID.randomUUID().toString().replaceAll("-", ""));
                zlRecord.setFilePath("/home/www/zlbg/"+ fileName1);
                zlRecord.setUserId(user.getUserId());
                zlRecord.setDeptId(user.getDeptId());
                newLabelMapper.insertZlRecord(zlRecord);
                try {
                    if (ObjectUtils.isEmpty(zlCount)){
                        newLabelMapper.updateDeptCount(user.getDeptId());
                    }else {
                        newLabelMapper.updateUserCount(user.getUserId());
                    }

                } catch (Exception e) {
                    throw new ServiceException("文件下载次数超限", HttpStatus.ERROR);
                }
            } else {
                System.out.println("文件下载失败,响应码:" + responseCode);
                throw new ServiceException("文件下载失败", HttpStatus.ERROR);
            }

            // 关闭连接
            connection.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
            throw new ServiceException("文件下载失败", HttpStatus.ERROR);
        }
        return AjaxResult.success("/home/www/zlbg/"+ fileName1);
    }

代理

public static String sendHttpPost(String encryptedMessage, String isProxy) throws Exception {
        try (CloseableHttpClient client = HttpClients.createDefault()) {
            HttpPost post = new HttpPost("https://szdymtx.suzhou.gov.cn/pay/query/cards");
            //设置代理配置
            if("true".equals(isProxy)){
                RequestConfig config = RequestConfig.custom()
                        .setSocketTimeout(15000)
                        .setConnectTimeout(15000)
                        .setConnectionRequestTimeout(15000)
                        .setProxy(new HttpHost("192.188.3.26", 28083))
                        .build();
                post.setConfig(config);
            }
            post.setHeader("Content-Type", "application/json");
            JSONObject dataBody = new JSONObject();
            dataBody.put("report_type", "pdf");
            dataBody.put("patent_number", zlRecord.getPatentNumber());
            StringEntity entity = new StringEntity(dataBody.toString(), "UTF-8");
            post.setEntity(entity);

            CloseableHttpResponse response = client.execute(post);
            String responseString = EntityUtils.toString(response.getEntity(), "UTF-8");
            return responseString;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

工具类

package com.ruoyi.bigscreen.zxAppCode.config;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

public class HttpUtils {

    /**
     * get
     *
     * @param host
     * @param path
     * @param method
     * @param headers
     * @param querys
     * @return
     * @throws Exception
     */
    public static HttpResponse doGet(String host, String path, String method,
                                     Map<String, String> headers,
                                     Map<String, String> querys)
            throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpGet request = new HttpGet(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        return httpClient.execute(request);
    }

    public static HttpResponse doGetNew(String host, String path, String method,
                                     Map<String, String> headers,
                                     Map<String, String> querys)
            throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpGet request = new HttpGet(buildUrl(host, path, querys));
        RequestConfig config = RequestConfig.custom()
                .setSocketTimeout(15000)
                .setConnectTimeout(15000)
                .setConnectionRequestTimeout(15000)
                .setProxy(new HttpHost("172.18.3.216", 28083))
                .build();
        request.setConfig(config);
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        return httpClient.execute(request);
    }

    /**
     * post form
     *
     * @param host
     * @param path
     * @param method
     * @param headers
     * @param querys
     * @param bodys
     * @return
     * @throws Exception
     */
    public static HttpResponse doPost(String host, String path, String method,
                                      Map<String, String> headers,
                                      Map<String, String> querys,
                                      Map<String, String> bodys)
            throws Exception {
        HttpClient httpClient = wrapClient(host);


        HttpPost request = new HttpPost(buildUrl(host, path, querys));

        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        if (bodys != null) {
            List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();

            for (String key : bodys.keySet()) {
                nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
            }
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
            formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
            request.setEntity(formEntity);
        }

        return httpClient.execute(request);
    }


    public static HttpResponse doPostNew(String host, String path, String method,
                                      Map<String, String> headers,
                                      Map<String, String> querys,
                                      Map<String, String> bodys)
            throws Exception {
        HttpClient httpClient = wrapClient(host);


        HttpPost request = new HttpPost(buildUrl(host, path, querys));
        RequestConfig config = RequestConfig.custom()
                .setSocketTimeout(15000)
                .setConnectTimeout(15000)
                .setConnectionRequestTimeout(15000)
                .setProxy(new HttpHost("172.18.3.216", 28083))
                .build();
        request.setConfig(config);
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        if (bodys != null) {
            List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();

            for (String key : bodys.keySet()) {
                nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
            }
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
            formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
            request.setEntity(formEntity);
        }

        return httpClient.execute(request);
    }

    /**
     * Post String
     *
     * @param host
     * @param path
     * @param method
     * @param headers
     * @param querys
     * @param body
     * @return
     * @throws Exception
     */
    public static HttpResponse doPost(String host, String path, String method,
                                      Map<String, String> headers,
                                      Map<String, String> querys,
                                      String body)
            throws Exception {
        HttpClient httpClient = wrapClient(host);
        HttpPost request = new HttpPost(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        if (StringUtils.isNotBlank(body)) {
            request.setEntity(new StringEntity(body, "utf-8"));
        }

        return httpClient.execute(request);
    }

    public static HttpResponse doPostNew(String host, String path, String method,
                                      Map<String, String> headers,
                                      Map<String, String> querys,
                                      String body)
            throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpPost request = new HttpPost(buildUrl(host, path, querys));
        RequestConfig config = RequestConfig.custom()
                .setSocketTimeout(15000)
                .setConnectTimeout(15000)
                .setConnectionRequestTimeout(15000)
                .setProxy(new HttpHost("172.18.3.216", 28083))
                .build();
        request.setConfig(config);
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        if (StringUtils.isNotBlank(body)) {
            request.setEntity(new StringEntity(body, "utf-8"));
        }

        return httpClient.execute(request);
    }

    /**
     * Post stream
     *
     * @param host
     * @param path
     * @param method
     * @param headers
     * @param querys
     * @param body
     * @return
     * @throws Exception
     */
    public static HttpResponse doPost(String host, String path, String method,
                                      Map<String, String> headers,
                                      Map<String, String> querys,
                                      byte[] body)
            throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpPost request = new HttpPost(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        if (body != null) {
            request.setEntity(new ByteArrayEntity(body));
        }

        return httpClient.execute(request);
    }

    /**
     * Put String
     * @param host
     * @param path
     * @param method
     * @param headers
     * @param querys
     * @param body
     * @return
     * @throws Exception
     */
    public static HttpResponse doPut(String host, String path, String method,
                                     Map<String, String> headers,
                                     Map<String, String> querys,
                                     String body)
            throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpPut request = new HttpPut(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        if (StringUtils.isNotBlank(body)) {
            request.setEntity(new StringEntity(body, "utf-8"));
        }

        return httpClient.execute(request);
    }

    /**
     * Put stream
     * @param host
     * @param path
     * @param method
     * @param headers
     * @param querys
     * @param body
     * @return
     * @throws Exception
     */
    public static HttpResponse doPut(String host, String path, String method,
                                     Map<String, String> headers,
                                     Map<String, String> querys,
                                     byte[] body)
            throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpPut request = new HttpPut(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        if (body != null) {
            request.setEntity(new ByteArrayEntity(body));
        }

        return httpClient.execute(request);
    }

    /**
     * Delete
     *
     * @param host
     * @param path
     * @param method
     * @param headers
     * @param querys
     * @return
     * @throws Exception
     */
    public static HttpResponse doDelete(String host, String path, String method,
                                        Map<String, String> headers,
                                        Map<String, String> querys)
            throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        return httpClient.execute(request);
    }

    private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException {
        StringBuilder sbUrl = new StringBuilder();
        sbUrl.append(host);
        if (!StringUtils.isBlank(path)) {
            sbUrl.append(path);
        }
        if (null != querys) {
            StringBuilder sbQuery = new StringBuilder();
            for (Map.Entry<String, String> query : querys.entrySet()) {
                if (0 < sbQuery.length()) {
                    sbQuery.append("&");
                }
                if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
                    sbQuery.append(query.getValue());
                }
                if (!StringUtils.isBlank(query.getKey())) {
                    sbQuery.append(query.getKey());
                    if (!StringUtils.isBlank(query.getValue())) {
                        sbQuery.append("=");
                        sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
                    }
                }
            }
            if (0 < sbQuery.length()) {
                sbUrl.append("?").append(sbQuery);
            }
        }

        return sbUrl.toString();
    }

    private static HttpClient wrapClient(String host) {
        HttpClient httpClient = new DefaultHttpClient();
        if (host.startsWith("https://")) {
            sslClient(httpClient);
        }

        return httpClient;
    }

    private static void sslClient(HttpClient httpClient) {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            X509TrustManager tm = new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
                public void checkClientTrusted(X509Certificate[] xcs, String str) {

                }
                public void checkServerTrusted(X509Certificate[] xcs, String str) {

                }
            };
            ctx.init(null, new TrustManager[] { tm }, null);
            SSLSocketFactory ssf = new SSLSocketFactory(ctx);
            ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            ClientConnectionManager ccm = httpClient.getConnectionManager();
            SchemeRegistry registry = ccm.getSchemeRegistry();
            registry.register(new Scheme("https", 443, ssf));
        } catch (KeyManagementException ex) {
            throw new RuntimeException(ex);
        } catch (NoSuchAlgorithmException ex) {
            throw new RuntimeException(ex);
        }
    }


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值