java调用保利威视频文件数据信息同步

先阐述一下,我们公司开通了直播模块,采用的就是保利威的平台,直播这一块主要是公司php那边负责的,我们这边需要把他们上传到保利威视频的信息存档,并且可以通过存档的链接在我们自己的平台上播放,这个文档的由来是因为保利威的官网上只有php的demo示例,我一开始自己写的调用各种的不成功,具体返回的code码忘了,然后和保利威那边的大神聊,各种的指导还是不成功,最后厚着脸皮问大神要了个他们的demo,目测应该是sha-1加密的方式不一样导致的,具体就不考究了,下面就是大神给我的demo我梳理了一下放上来,做个参考

1.http请求工具类

package com.xxx.xxx.xxx.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.net.ssl.SSLContext;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.NoHttpResponseException;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.ServiceUnavailableRetryStrategy;
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.HttpHead;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.HttpClientUtils;
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.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * httpclient的操作实现类
 */
public class HttpClientUtil {
    
    private static final Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
    private static final int MAX_LEN = 1024;
    private static final String DEFAULT_CHARSET = "UTF-8";
    //注意:如果是进行视频的上传的 话这里要把时间设置的长一些
    private RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000)
            .setConnectionRequestTimeout(10000).build();
    
    // 超时时间为5分钟,用于一些等待时间较长的请求
    private RequestConfig longTimeRequestConfig = RequestConfig.custom()
            .setSocketTimeout(300000)
            .setConnectTimeout(300000)
            .setConnectionRequestTimeout(300000)
            .build();
    
    private static HttpClientUtil instance = null;
    
    private HttpClient ignoreSSLClient;
    
    private HttpClient client;
    
    private HttpClient retryClient;
    
    private HttpClientUtil() {
        this.ignoreSSLClient = createHttpsClient(true);
        this.client = createHttpsClient(false);
        this.retryClient = createHttpsClientWithRetry();
    }
    
    public static HttpClientUtil getInstance() {
        if (instance == null) {
            instance = new HttpClientUtil();
        }
        return instance;
    }
    
    private HttpClient getHttpClient(boolean ignoreSSL) {
        return ignoreSSL ? ignoreSSLClient : client;
    }

    /**
     * 发送 post请求
     * @param httpUrl 地址
     * @param maps 参数
     */
    public String sendHttpPost(String httpUrl, Map maps) {
        // 创建httpPost
        HttpPost httpPost = new HttpPost(httpUrl);
        // 创建参数队列
        List nameValuePairs = new ArrayList<>();
        for (String key : maps.keySet()) {
            nameValuePairs.add(new BasicNameValuePair(key, maps.get(key)));
        }
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, DEFAULT_CHARSET));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return sendHttpPost(httpPost);
    }

    /**
     * 发送Post请求
     * @param httpPost post请求
     * @return 响应内容
     */
    private String sendHttpPost(HttpPost httpPost) {
        return sendHttpRequest(httpPost);
    }

    /**
     * 发送Get请求
     * @return 成功时为响应内容,失败时为 null
     */
    private String sendHttpRequest(HttpRequestBase requestBase) {
        return sendHttpRequest(requestBase, false);
    }

    /**
     * 发送请求
     * @return 成功时为响应内容,失败时为 null
     */
    private String sendHttpRequest(HttpRequestBase requestBase, boolean ignoreSslCerts) {
        return sendHttpRequest(requestBase, ignoreSslCerts, false);
    }

    /**
     * 发送请求
     * @param needLongTime 请求花费时间是否需要较长等待时间
     * @return 成功时为响应内容,失败时为 null
     */
    private String sendHttpRequest(HttpRequestBase requestBase, boolean ignoreSslCerts, Boolean needLongTime) {
        HttpResponse response = null;
        HttpEntity entity;
        try {
            // 创建默认的httpClient实例.
            if (null == needLongTime || !needLongTime) {
                requestBase.setConfig(requestConfig);
            } else {
                requestBase.setConfig(longTimeRequestConfig);
            }
            // 执行请求
            response = getHttpClient(ignoreSslCerts).execute(requestBase);
            entity = response.getEntity();
            return EntityUtils.toString(entity, "UTF-8");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            HttpClientUtils.closeQuietly(response);
        }
        return null;
    }

    /**
     * 发送 post请求
     * @param httpUrl 地址
     */
    public String sendHttpPost(String httpUrl) {
        HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
        return sendHttpPost(httpPost);
    }
    
    /**
     * 发送 post请求
     * @param httpUrl 地址
     */
    public String sendHttpPost(String httpUrl, boolean ignoreSsl) {
        HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
        return sendHttpRequest(httpPost, ignoreSsl);
    }
    
    /**
     * 发送 post请求(带重试机制)
     * @param httpUrl 地址
     * @param maps 参数
     */
    //
    public String sendHttpPostWithRetry(String httpUrl, Map maps) {
        // 创建httpPost
        HttpPost httpPost = new HttpPost(httpUrl);
        // 创建参数队列
        List nameValuePairs = new ArrayList<>();
        for (String key : maps.keySet()) {
            nameValuePairs.add(new BasicNameValuePair(key, maps.get(key)));
        }
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return sendHttpRequestWithRetry(httpPost, this.retryClient);
    }
    

    
    
    /**
     * 发送Post请求(带重试机制)
     * @param request post请求
     * @return 请求结果
     */
    private String sendHttpRequestWithRetry(HttpRequestBase request, HttpClient retryClient) {
        HttpResponse response = null;
        HttpEntity entity;
        String responseContent = null;
        try {
            // 创建默认的httpClient实例.
            request.setConfig(requestConfig);
            // 执行请求
            response = retryClient.execute(request);
            entity = response.getEntity();
            responseContent = EntityUtils.toString(entity, "UTF-8");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            HttpClientUtils.closeQuietly(response);
        }
        return responseContent;
    }
    
    /**
     * 发送 post请求
     * @param httpUrl 地址
     * @param params 参数(格式:json格式的内容)
     * @param headers header头信息
     */
    public String sendHttpPostJson(String httpUrl, String params, Map headers) {
        HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
        setPostContent(params, headers, httpPost);
        return sendHttpPost(httpPost);
    }   
    
    /**
     * 发送 post请求
     * @param httpUrl 地址
     * @param params 参数(格式:json格式的内容)
     * @param headers header头信息
     */
    public String sendHttpPostJsonIgnoreSsl(String httpUrl, String params, Map headers) {
        HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
        setPostContent(params, headers, httpPost);
        return sendHttpRequest(httpPost, true);
    }
    
    private void setPostContent(String params, Map headers, HttpPost httpPost) {
        try {
            // 设置参数
            StringEntity stringEntity = new StringEntity(params, DEFAULT_CHARSET);
            stringEntity.setContentType("application/json");
            httpPost.setEntity(stringEntity);
            if (null != headers && headers.size() > 0) {
                for (String name : headers.keySet()) {
                    httpPost.addHeader(name, headers.get(name));
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }
    
    /**
     * 发送 post请求
     * @param httpUrl 地址
     * @param params 参数(格式:json格式的内容)
     * @param headers 请求头
     * @param ignoreSsl 是否跳过证书校验,true为跳过 false为不跳过
     */
    public String sendHttpPostJson(String httpUrl, String params, Map headers, boolean ignoreSsl) {
        // 创建httpPost
        HttpPost httpPost = new HttpPost(httpUrl);
        try {
            // 设置参数
            StringEntity stringEntity = new StringEntity(params, "UTF-8");
            stringEntity.setContentType("application/json");
            httpPost.setEntity(stringEntity);
            if (null != headers && headers.size() > 0) {
                for (String name : headers.keySet()) {
                    httpPost.addHeader(name, headers.get(name));
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return sendHttpRequest(httpPost, ignoreSsl);
    }
    
    /**
     * 发送 delete请求
     * @param httpUrl 地址
     * @param ignoreSsl 是否跳过证书校验,true为跳过 false为不跳过
     */
    public String sendHttpDelete(String httpUrl, boolean ignoreSsl) {
        // 创建httpPost
        HttpDelete httpPost = new HttpDelete(httpUrl);
        return sendHttpRequest(httpPost, ignoreSsl);
    }
    
    /**
     * 发送 post请求
     * @param httpUrl 地址
     * @param params 参数(格式:json格式的内容)
     * @param headers header头信息
     */
    public File sendHttpPostJsonFile(String httpUrl, String params, Map headers, File file) {
        // 创建httpPost
        HttpPost httpPost = new HttpPost(httpUrl);
        setPostContent(params, headers, httpPost);
        return sendHttpPostResponseFile(httpPost, file);
    }
    
    /**
     * 发送 post请求
     * @param httpUrl 地址
     * @param params 参数(格式:key1=value1&key2=value2)
     */
    public String sendHttpPost(String httpUrl, String params) {
        // 创建httpPost
        HttpPost httpPost = new HttpPost(httpUrl);
        try {
            // 设置参数
            StringEntity stringEntity = new StringEntity(params, DEFAULT_CHARSET);
            stringEntity.setContentType("application/x-www-form-urlencoded");
            httpPost.setEntity(stringEntity);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return sendHttpPost(httpPost);
    }
    
    /**
     * 发送 post请求
     * @param httpUrl 地址
     * @param params 参数(格式:key1=value1&key2=value2)
     */
    public String sendHttpPost(String httpUrl, String params, boolean ignoreSsl) {
        // 创建httpPost
        HttpPost httpPost = new HttpPost(httpUrl);
        try {
            // 设置参数
            StringEntity stringEntity = new StringEntity(params, DEFAULT_CHARSET);
            stringEntity.setContentType("application/x-www-form-urlencoded");
            httpPost.setEntity(stringEntity);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return sendHttpRequest(httpPost, ignoreSsl);
    }
    
    /**
     * 发送 post请求
     * @param httpUrl 地址
     * @param headers header头信息
     * @param params 参数(格式:key1=value1&key2=value2)
     */
    public String sendHttpPostWithHeader(String httpUrl, String params, Header[] headers) {
        // 创建httpPost
        HttpPost httpPost = new HttpPost(httpUrl);
        try {
            httpPost.setHeaders(headers);
            // 设置参数
            StringEntity stringEntity = new StringEntity(params, DEFAULT_CHARSET);
            stringEntity.setContentType("application/x-www-form-urlencoded");
            httpPost.setEntity(stringEntity);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return sendHttpPost(httpPost);
    }

    /**
     * 发送 post请求
     * @param httpUrl 地址
     * @param maps 参数
     */
    public String sendHttpPost(String httpUrl, Map maps, boolean ignoreSsl) {
        // 创建httpPost
        HttpPost httpPost = new HttpPost(httpUrl);
        // 创建参数队列
        List nameValuePairs = new ArrayList<>();
        for (String key : maps.keySet()) {
            nameValuePairs.add(new BasicNameValuePair(key, maps.get(key)));
        }
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, DEFAULT_CHARSET));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return sendHttpRequest(httpPost, ignoreSsl);
    }
    
    /**
     * 发送 get请求
     * @param httpUrl 地址
     * @param headers header头信息
     */
    public String sendHttpGet(String httpUrl, Map headers) {
        // 创建httpGet
        HttpGet httpGet = new HttpGet(httpUrl);
        try {
            if (null != headers && headers.size() > 0) {
                for (String name : headers.keySet()) {
                    httpGet.addHeader(name, headers.get(name));
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return sendHttpGet(httpGet);
    }
    
    /**
     * 发送 带有自定义header的post请求
     * @param httpUrl 地址
     * @param maps 参数
     * @param headers 自定义headers
     * @param needLongTime 请求是否需要消耗比较长时间
     */
    public String sendHttpPostWithHeader(String httpUrl, Map maps, Header[] headers,
            boolean needLongTime) {
        HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
        httpPost.setHeaders(headers);
        // 创建参数队列
        List nameValuePairs = new ArrayList<>();
        for (String key : maps.keySet()) {
            nameValuePairs.add(new BasicNameValuePair(key, maps.get(key)));
        }
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, DEFAULT_CHARSET));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return sendHttpRequest(httpPost, false, needLongTime);
    }
    
    /**
     * 发送 post请求(带文件)
     * @param httpUrl 地址
     * @param maps 参数
     * @param fileLists 附件
     */
    public String sendHttpPost(String httpUrl, Map maps, List fileLists) {
        HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
        MultipartEntityBuilder meBuilder = MultipartEntityBuilder.create();
        for (String key : maps.keySet()) {
        	//这里的话一般是文本类型ContentType.TEXT_PLAIN,但是如果是json格式的话就是的换成下面的形式
            meBuilder.addPart(key, new StringBody(maps.get(key), ContentType.APPLICATION_JSON));
        }
        for (File file : fileLists) {
            FileBody fileBody = new FileBody(file);
            //注意:这里的Filedata是在上传视频的时候使用的,如果是其他情况下要做改变,例如白名单就要使用file,是根据文档的参数来的,不是文件的名字
            meBuilder.addPart("Filedata", fileBody);
        }
        HttpEntity reqEntity = meBuilder.build();
        httpPost.setEntity(reqEntity);
        return sendHttpPost(httpPost);
    }

    /**
     * 发送Post请求
     * @param httpPost post请求
     * @return 请求内容
     */
    private File sendHttpPostResponseFile(HttpPost httpPost, File file) {
        HttpResponse response = null;
        OutputStream outputStream = null;
        try {
            // 创建默认的httpClient实例.
            httpPost.setConfig(requestConfig);
            // 执行请求
            response = getHttpClient(false).execute(httpPost);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            
            if (!file.exists()) {
                file.createNewFile();
            }
            outputStream = new FileOutputStream(file);
            int len;
            byte[] buf = new byte[MAX_LEN];
            while ((len = response.getEntity().getContent().read(buf, 0, MAX_LEN)) != -1) {
                outputStream.write(buf, 0, len);
            }
            outputStream.flush();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            HttpClientUtils.closeQuietly(response);
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    logger.error("close file outputstream exception", e);
                }
            }
        }
        return file;
    }
    
    /**
     * 发送 get请求
     * @return 成功时为响应内容,失败时为 null
     */
    public String sendHttpGet(String httpUrl) {
        HttpGet httpGet = new HttpGet(httpUrl);// 创建get请求
        //httpGet.setHeader("Host", "112.74.30.89 api.polyv.net");
        return sendHttpGet(httpGet);
    }
    
    /**
     * 发送 get请求Https
     * @param httpUrl 请求的路径
     * @param ignoreSSLCerts 是否忽略证书校验
     */
    public String sendHttpsGet(String httpUrl, boolean ignoreSSLCerts) {
        HttpGet httpGet = new HttpGet(httpUrl);// 创建get请求
        return sendHttpsGet(httpGet, ignoreSSLCerts);
    }
    
    /**
     * 发送http delete请求
     */
    public String sendHttpDelete(String httpUrl) {
        HttpDelete httpDelete = new HttpDelete(httpUrl);
        return sendHttpRequest(httpDelete);
    }
    
    /**
     * 发送 get请求Https
     * @param httpUrl 请求的路径
     * @param ignoreSSLCerts 是否忽略证书校验
     */
    public Integer sendHttpsGetForStatus(String httpUrl, boolean ignoreSSLCerts) {
        HttpGet httpGet = new HttpGet(httpUrl);// 创建get请求
        return sendHttpsGetForStatus(httpGet, ignoreSSLCerts);
    }
    
    /**
     * 发送 get请求Https
     * @param httpUrl 请求的路径
     * @param ignoreSSLCerts 是否忽略证书校验
     * @param requestConfig 请求的配置信息
     */
    public Integer sendHttpsGetForStatus(String httpUrl, boolean ignoreSSLCerts, RequestConfig requestConfig) {
        HttpGet httpGet = new HttpGet(httpUrl);// 创建get请求
        return sendHttpsGetForStatus(httpGet, ignoreSSLCerts, requestConfig);
    }
    
    /**
     * 通过Head请求校验url是否有效,只有状态码为200时,链接为有效
     * @param httpUrl 地址
     * @return true/false
     */
    public boolean isValidUrl(String httpUrl) {
        HttpHead httpHead = new HttpHead(httpUrl);
        HttpResponse response = null;
        try {
            response = createHttpsClient(false).execute(httpHead);
            logger.info("validate url[{}] status code[{}]", httpUrl, response.getStatusLine().getStatusCode());
            return response.getStatusLine().getStatusCode() == 200;
        } catch (IOException e) {
            logger.error("httpHead error url[{}]", httpUrl, e);
            HttpClientUtils.closeQuietly(response);
        }
        return false;
    }
    
    /**
     * 发送Get请求
     * @return 成功时为响应内容,失败时为 null
     */
    private String sendHttpGet(HttpGet httpGet) {
        return sendHttpRequest(httpGet);
    }
    
    /**
     * 发送带重试的get请求
     * @param httpUrl url
     * @param retry 重试次数
     * @param interval 重试间隔
     * @return
     */
    public String sendHttpGetWithRetry(String httpUrl, int retry, long interval) {
        HttpClient retryClient = createHttpsClientWithRetry(retry, interval);
        return sendHttpRequestWithRetry(new HttpGet(httpUrl), retryClient);
    }
    

    /**
     * 发送Get请求Https
     * ignoreSSLCerts参数为true可以忽略证书和域名的校验,可以避免 {@link }
     * @param httpGet 使用https发送get请求
     * @param ignoreSSLCerts 忽略证书和域名校验
     * @return 返回内容
     */
    private String sendHttpsGet(HttpGet httpGet, boolean ignoreSSLCerts) {
        HttpResponse response = null;
        String responseContent = null;
        try {
            httpGet.setConfig(requestConfig);
            // 执行请求
            response = getHttpClient(ignoreSSLCerts).execute(httpGet);
            HttpEntity entity = response.getEntity();
            responseContent = EntityUtils.toString(entity, DEFAULT_CHARSET);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            HttpClientUtils.closeQuietly(response);
        }
        return responseContent;
    }
    
    /**
     * 发送Get请求Https
     * ignoreSSLCerts参数为true可以忽略证书和域名的校验,可以避免 {@link }
     * @param httpGet 使用https发送get请求
     * @param ignoreSSLCerts 忽略证书和域名校验
     * @return 返回内容
     */
    private Integer sendHttpsGetForStatus(HttpGet httpGet, boolean ignoreSSLCerts) {
        HttpResponse response = null;
        Integer responseCode = null;
        try {
            httpGet.setConfig(requestConfig);
            // 执行请求
            response = getHttpClient(ignoreSSLCerts).execute(httpGet);
            HttpEntity entity = response.getEntity();
            logger.info("get url {},response {}", httpGet.getURI(),
                    EntityUtils.toString(entity, DEFAULT_CHARSET));
            responseCode = response.getStatusLine().getStatusCode();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            HttpClientUtils.closeQuietly(response);
        }
        return responseCode;
    }
    
    /**
     * 发送Get请求Https
     * ignoreSSLCerts参数为true可以忽略证书和域名的校验,可以避免 }
     * @param httpGet 使用https发送get请求
     * @param ignoreSSLCerts 忽略证书和域名校验
     * @param requestConfig 配置可自定义
     * @return 返回内容
     */
    private Integer sendHttpsGetForStatus(HttpGet httpGet, boolean ignoreSSLCerts, RequestConfig requestConfig) {
        HttpResponse response = null;
        Integer responseCode = null;
        try {
            httpGet.setConfig(requestConfig);
            // 执行请求
            response = getHttpClient(ignoreSSLCerts).execute(httpGet);
            HttpEntity entity = response.getEntity();
            logger.info("get url {},response {}", httpGet.getURI(), EntityUtils.toString(entity, DEFAULT_CHARSET));
            responseCode = response.getStatusLine().getStatusCode();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            HttpClientUtils.closeQuietly(response);
        }
        return responseCode;
    }
    
    /**
     * 初始化https请求Client
     * @param ignoreSSLCerts 忽略证书
     */
    public CloseableHttpClient createHttpsClient(boolean ignoreSSLCerts) {
        CloseableHttpClient httpClient;
        if (ignoreSSLCerts) {
            SSLContext ctx = null;
            try {
                // 忽略客户端证书校验
                ctx = new org.apache.http.conn.ssl.SSLContextBuilder().loadTrustMaterial(null, (chain, authType) -> true).build();
            } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
                logger.error("create ssl context error", e);
            }
            
            // 忽略证书和hostName校验
            httpClient = HttpClients.custom()
                    .setDefaultRequestConfig(requestConfig)
                    .setSSLHostnameVerifier((host, session) -> true)
                    .setSSLSocketFactory(new SSLConnectionSocketFactory(ctx)).build();
        } else {
            httpClient = HttpClients.createDefault();
        }
        return httpClient;
    }
    
    /**
     * 初始化http请求Client(带重试机制)默认重试3次,间隔3秒
     */
    public CloseableHttpClient createHttpsClientWithRetry() {
        return createHttpsClientWithRetry(3, 3000L);
    }
    
    /**
     * 初始化http请求Client(带重试机制)
     * @param retry 重试次数
     * @param interval 重试时间间隔(毫秒)
     * @return
     */
    public CloseableHttpClient createHttpsClientWithRetry(int retry, long interval) {
        // 请求错误处理
        ServiceUnavailableRetryStrategy strategy = new ServiceUnavailableRetryStrategy() {
            /**
             * retry逻辑
             */
            @Override
            public boolean retryRequest(HttpResponse response, int executionCount, HttpContext context) {
                StatusLine statusLine = response.getStatusLine();
                int code = statusLine.getStatusCode();
                if (404 == code || 500 == code || 501 == code || 502 == code || 503 == code || 504 == code) {
                    logger.info("request url error, code:{}", code);
                    return executionCount < retry;
                }
                return false;
            }
            
            /**
             * retry间隔时间
             */
            @Override
            public long getRetryInterval() {
                return interval;
            }
        };
        
        // 异常处理
        HttpRequestRetryHandler handler = (arg0, retryTimes, arg2) -> {
            logger.error("request occur an exception, retry = {}", retryTimes);
            if (arg0 instanceof UnknownHostException
                    || arg0 instanceof NoHttpResponseException) {
                // 间隔3秒重新请求
                try {
                    Thread.sleep(interval);
                } catch (InterruptedException e) {
                    logger.error(e.getMessage(), e);
                }
                return retryTimes < retry;
            }
            return false;
        };
        return HttpClients.custom().setRetryHandler(handler).setServiceUnavailableRetryStrategy(strategy).build();
    }
    
    public Map getResponseHeader(String url) {
        HttpHead httpHead = new HttpHead(url);
        HttpResponse response = null;
        try {
            response = getHttpClient(Boolean.TRUE).execute(httpHead);
            Header[] headers = response.getAllHeaders();
            
            return Arrays.stream(headers).collect(Collectors.toMap(Header::getName, Header::getValue));
        } catch (IOException e) {
            logger.error("httpHead error url[{}]", url, e);
            HttpClientUtils.closeQuietly(response);
        }
        return Collections.emptyMap();
    }
    
    /**
     * 初始化https请求Client
     * @param ignoreSSLCerts 忽略证书
     */
    public CloseableHttpClient createHttpClientWithCOnfig(RequestConfig requestConfig, boolean ignoreSSLCerts) {
        CloseableHttpClient httpClient;
        if (ignoreSSLCerts) {
            SSLContext ctx = null;
            try {
                // 忽略客户端证书校验
            	//SSLContextBuilder
                ctx = new org.apache.http.conn.ssl.SSLContextBuilder().loadTrustMaterial(null, (chain, authType) -> true).build();
            } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
                logger.error("create ssl context error", e);
            }
            
            // 忽略证书和hostName校验
            httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig)
                    .setSSLHostnameVerifier((host, session) -> true)
                    .setSSLSocketFactory(new SSLConnectionSocketFactory(ctx)).build();
        } else {
            httpClient = HttpClients.createDefault();
        }
        return httpClient;
    }
    
}

2.加密的工具类(包含md5和sha加密,我们这里只用了sha)

package com.xxx.xxx.common.utils;

import org.apache.commons.codec.digest.DigestUtils;

/**
 * 加密工具类。
 * @author
 */
public class EncryptionUtils {

    /**
     * 对字符串做MD5加密,返回加密后的字符串。
     * @param text 待加密的字符串。
     * @return 加密后的字符串。
     */
    public static String md5Hex(String text) {
        return DigestUtils.md5Hex(text);
    }

    /**
     * 对字符串做SHA-1加密,返回加密后的字符串。
     * @param text 待加密的字符串。
     * @return 加密后的字符串。
     */
    public static String shaHex(String text) {
        return DigestUtils.sha1Hex(text);
    }

    /**
     * 对字符串做SHA-1加密,然后截取前面20个字符(遗留OVP系统的密码验证方式)。
     * @param text 待加密的字符串。
     * @return 加密后的前20个字符。
     */
    public static String getLittleSHA1(String text) {
        String encryptedStr = DigestUtils.sha1Hex(text).toUpperCase();
        return encryptedStr.substring(0, 20);
    }

    public static void main(String[] args) {
        System.out.println(EncryptionUtils.md5Hex("javas"));
    }
}

3.调用逻辑

 @RequestMapping(value = "/synchroVideo",method = RequestMethod.POST)
    @Transactional(rollbackFor = MyException.class)
    public Result synchroVideo(@RequestParam(required = true) int type) throws ParseException {
        //获取保利威基本参数
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String userid = "9999999";//保利威userId
        String secureKey ="123456789";//secureKey
        String url = "http://api.polyv.net/v2/video/"+userid+"/get-new-list";
        String catatree = "1"; //保利威视频所在分类树,默认为1(1为全部分类内数据)
        String numPerPage= "1000";//平均每页取多少条数据
        String pageNum = "1";//取第几页
        //获取最后一次同步跟新时间(官方接口文档里面有个时间区间,这里根据自己的逻辑来)
        String startTime=videoManageService.selectLastTime();
        String ptime = Long.toString(System.currentTimeMillis());//当前时间的时间戳
        String signSource="";
        Map map = new HashMap();
        if (type==0){ //根据上一次更新时间获取之后所有数据
            //catatree=参数&endDate=参数&format=参数&jsonp=参数&numPerPage=参数&pageNum=参数&ptime=参数&startDate=参数secureKey
            signSource = "catatree="+catatree+"&numPerPage="+numPerPage+"&pageNum="+pageNum+"&ptime="+ptime+"&startTime="+startTime+secureKey;
            map.put("startTime",startTime);
        }else if (type==1){ //获取从开始到当前的所有数据
            signSource = "catatree="+catatree+"&numPerPage="+numPerPage+"&pageNum="+pageNum+"&ptime="+ptime+secureKey;
        }
        //sha-1 加密并将所有字母转移成大写
        String sign = EncryptionUtils.shaHex(signSource).toUpperCase();
        map.put("catatree", catatree);
        map.put("numPerPage", numPerPage);
        map.put("pageNum", pageNum);
        map.put("ptime", ptime);
        map.put("sign", sign);
        //http 请求
        String message = HttpClientUtil.getInstance().sendHttpPost(url, map);
        System.out.println(message);
        JSONObject jsonObject=JSONObject.fromObject(message);
        if (jsonObject.get("code").equals("400")){
            return new ResultUtil<>().setErrorMsg("保利威拉取失败:"+jsonObject.get("message"));
        }
        return new ResultUtil<>().setSuccessMsg("拉取存入成功");
    } 
  

 

你可能感兴趣的:(参考类,java,java)