赞
踩
因为在项目中需要使用阿里云的视频点播服务,需要获取视频点播的时长信息。
生成签名串Signature
SignatureUtils.java
package com.meeno.wzq.alibaba.signature; import com.google.common.collect.Maps; import com.meeno.framework.util.HttpUtils; import lombok.extern.java.Log; import sun.misc.BASE64Encoder; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.security.SignatureException; import java.text.SimpleDateFormat; import java.util.*; /** * @description: 生成签名串Signature * @author: Wzq * @create: 2020-01-14 17:38 */ @Log public class SignatureUtils { /*对所有参数名称和参数值做URL编码*/ public static List<String> getAllParams(Map<String, String> publicParams, Map<String, String> privateParams) { List<String> encodeParams = new ArrayList<String>(); if (publicParams != null) { for (String key : publicParams.keySet()) { String value = publicParams.get(key); //将参数和值都urlEncode一下。 String encodeKey = percentEncode(key); String encodeVal = percentEncode(value); encodeParams.add(encodeKey + "=" + encodeVal); } } if (privateParams != null) { for (String key : privateParams.keySet()) { String value = privateParams.get(key); //将参数和值都urlEncode一下。 String encodeKey = percentEncode(key); String encodeVal = percentEncode(value); encodeParams.add(encodeKey + "=" + encodeVal); } } return encodeParams; } /*获取 CanonicalizedQueryString*/ public static String getCQS(List<String> allParams) { ParamsComparator paramsComparator = new ParamsComparator(); Collections.sort(allParams, paramsComparator); String cqString = ""; for (int i = 0; i < allParams.size(); i++) { cqString += allParams.get(i); if (i != allParams.size() - 1) { cqString += "&"; } } return cqString; } /*字符串参数比较器,按字母序升序*/ public static class ParamsComparator implements Comparator<String> { @Override public int compare(String lhs, String rhs) { return lhs.compareTo(rhs); } } public static byte[] hmacSHA1Signature(String accessKeySecret, String stringToSign) { try { String key = accessKeySecret + "&"; try { SecretKeySpec signKey = new SecretKeySpec(key.getBytes(), "HmacSHA1"); Mac mac = Mac.getInstance("HmacSHA1"); mac.init(signKey); return mac.doFinal(stringToSign.getBytes()); } catch (Exception e) { throw new SignatureException("Failed to generate HMAC : " + e.getMessage()); } } catch (SignatureException e) { e.printStackTrace(); } return null; } public static String newStringByBase64(byte[] bytes) throws UnsupportedEncodingException { if (bytes == null || bytes.length == 0) { return null; } return new String(new BASE64Encoder().encode(bytes)); } /*特殊字符替换为转义字符*/ public static String percentEncode(String value) { try { String urlEncodeOrignStr = URLEncoder.encode(value, "UTF-8"); String plusReplaced = urlEncodeOrignStr.replace("+", "%20"); String starReplaced = plusReplaced.replace("*", "%2A"); String waveReplaced = starReplaced.replace("%7E", "~"); return waveReplaced; } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return value; } /*生成当前UTC时间戳Time*/ public static String generateTimestamp() { Date date = new Date(System.currentTimeMillis()); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); df.setTimeZone(new SimpleTimeZone(0, "GMT")); return df.format(date); } /*生成随机数SignatureNonce*/ public static String generateRandom() { String signatureNonce = UUID.randomUUID().toString(); return signatureNonce; } }
httpUtils.java
请求工具类
package com.meeno.framework.util; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.google.common.collect.Lists; import com.meeno.encryptionmodule.testPaper.service.TestpaperServiceImpl; import com.meeno.wzq.config.PlatformServerConfig; import com.meeno.wzq.constants.EncryptionConstants; import com.meeno.wzq.constants.PlatformUrlEnum; import org.apache.http.*; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.HttpRequestRetryHandler; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.conn.ConnectTimeoutException; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.CoreConnectionPNames; import org.apache.http.protocol.HttpContext; import java.io.*; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URI; import java.net.UnknownHostException; import java.util.*; /** * @Auther: Wzq * @Date: 2019/4/2 11:20 * @Description: 得不到的永远在骚动,被偏爱的都有恃无恐。 -- HttpUtils */ public class HttpUtils { private final static PoolingHttpClientConnectionManager poolConnManager = new PoolingHttpClientConnectionManager(); //连接池管理器 private final static HttpRequestRetryHandler httpRequestRetryHandler = new HttpRequestRetryHandler() { //retry handler public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { if (executionCount >= 5) { return false; } if (exception instanceof NoHttpResponseException) { return true; } if (exception instanceof InterruptedIOException) { return false; } if (exception instanceof UnknownHostException) { return false; } if (exception instanceof ConnectTimeoutException) { return false; } HttpClientContext clientContext = HttpClientContext .adapt(context); HttpRequest request = clientContext.getRequest(); if (!(request instanceof HttpEntityEnclosingRequest)) { return true; } return false; } }; static { //类加载的时候 设置最大连接数 和 每个路由的最大连接数 poolConnManager.setMaxTotal(200000); poolConnManager.setDefaultMaxPerRoute(100000); } /** * ########################### core code####################### * @return */ private static CloseableHttpClient getCloseableHttpClient() { CloseableHttpClient httpClient = HttpClients.custom() .setConnectionManager(poolConnManager) .setRetryHandler(httpRequestRetryHandler) .build(); return httpClient; } /** * 封装HTTP GET方法 * 有参数的Get请求 * @param * @param * @return * @throws ClientProtocolException * @throws java.io.IOException */ public static String getAjax(String url, Map<String, String> paramMap) throws ClientProtocolException, IOException { HttpClient httpClient = getCloseableHttpClient(); HttpGet httpGet = new HttpGet(); List<NameValuePair> formparams = setHttpParams(paramMap); String param = URLEncodedUtils.format(formparams, "UTF-8"); httpGet.setURI(URI.create(url + "?" + param)); HttpResponse response = httpClient.execute(httpGet); String httpEntityContent = getHttpEntityContent(response); httpGet.abort(); return httpEntityContent; } /** * 封装HTTP GET方法 * 有参数的Get请求 * @param * @param * @return * @throws ClientProtocolException * @throws java.io.IOException */ public static String get(String url, Map<String, String> paramMap) throws ClientProtocolException, IOException { paramMap = getParamsData(paramMap); HttpClient httpClient = getCloseableHttpClient(); HttpGet httpGet = new HttpGet(); List<NameValuePair> formparams = setHttpParams(paramMap); String param = URLEncodedUtils.format(formparams, "UTF-8"); httpGet.setURI(URI.create(url + "?" + param)); HttpResponse response = httpClient.execute(httpGet); String httpEntityContent = getHttpEntityContent(response); httpGet.abort(); return httpEntityContent; } /** * 封装HTTP GET方法 * 无参数的Get请求 * @param * @return * @throws ClientProtocolException * @throws java.io.IOException */ public static String get(String url) throws ClientProtocolException, IOException { //首先需要先创建一个DefaultHttpClient的实例 HttpClient httpClient = new DefaultHttpClient(); //先创建一个HttpGet对象,传入目标的网络地址,然后调用HttpClient的execute()方法即可: HttpGet httpGet = new HttpGet(); httpGet.setURI(URI.create(url)); HttpResponse response = httpClient.execute(httpGet); String httpEntityContent = getHttpEntityContent(response); httpGet.abort(); return httpEntityContent; } /** * 获得响应HTTP实体内容 * @param response * @return * @throws java.io.IOException * @throws java.io.UnsupportedEncodingException */ private static String getHttpEntityContent(HttpResponse response) throws IOException, UnsupportedEncodingException { //通过HttpResponse 的getEntity()方法获取返回信息 HttpEntity entity = response.getEntity(); if (entity != null) { InputStream is = entity.getContent(); BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")); String line = br.readLine(); StringBuilder sb = new StringBuilder(); while (line != null) { sb.append(line + "\n"); line = br.readLine(); } br.close(); is.close(); return sb.toString(); } return ""; } /** * 封装支付HTTP POST方法 * @param * @param * @return * @throws ClientProtocolException * @throws java.io.IOException */ public static String postPayMsg(String url, Map<String, String> paramMap) throws ClientProtocolException, IOException { HttpClient httpClient = new DefaultHttpClient(); httpClient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000); httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 3000); HttpPost httpPost = new HttpPost(url); paramMap = getParamsData(paramMap); List<NameValuePair> formparams = setHttpParams(paramMap); UrlEncodedFormEntity param = new UrlEncodedFormEntity(formparams, "UTF-8"); //通过setEntity()设置参数给post httpPost.setEntity(param); //利用httpClient的execute()方法发送请求并且获取返回参数 HttpResponse response = httpClient.execute(httpPost); String httpEntityContent = getHttpEntityContent(response); httpPost.abort(); return httpEntityContent; } /** * 设置请求参数 * @param * @return */ private static List<NameValuePair> setHttpParams(Map<String, String> paramMap) { List<NameValuePair> formparams = new ArrayList<NameValuePair>(); Set<Map.Entry<String, String>> set = paramMap.entrySet(); for (Map.Entry<String, String> entry : set) { formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } return formparams; } public static Map<String,String> getParamsData(Map<String,String> paramsMap){ Map<String,String> params = new HashMap<>(); String dataJson = JSONObject.toJSONString(paramsMap); params.put("Data",dataJson); return params; } /** * @描述: 获取http请求的JSONObject * @参数: [jsonStr] * @返回值: com.alibaba.fastjson.JSONObject * @创建人 WZQ * @创建时间: 11:38 2019/4/2 */ public static JSONObject getResponseJson(String jsonStr){ JSONObject jsonObject = JSONObject.parseObject(jsonStr); return jsonObject; } /** * @描述: 获取新增返回的data id * @参数: [jsonStr] * @返回值: java.lang.Long * @创建人 WZQ * @创建时间: 11:38 2019/4/2 */ public static Long getResponseData(String jsonStr){ return JSONObject.parseObject(jsonStr).getLong("data"); } /** * @描述: 执行获取Id * @参数: [url, paramsMap] * @返回值: java.lang.Long * @创建人 WZQ * @创建时间: 17:24 2019/4/2 */ /* public static Long executeHttpGetId(String url,Map<String,String> paramsMap){ // JSONObject jsonObject = executeHttp(url,paramsMap); System.out.println(url); String getStr = null; try { getStr = get(url,paramsMap); } catch (IOException e) { e.printStackTrace(); } return JSONObject.parseObject(getStr).getLong("data"); }*/ /** * @描述: 执行返回JSONArr * @参数: [utl, paramsMap] * @返回值: java.lang.String * @创建人 WZQ * @创建时间: 17:17 2019/4/2 */ public static JSONArray executeHttpGetResultArr(String url, Map<String,String> paramsMap){ System.out.println(url); String getStr = null; try { getStr = get(url,paramsMap); } catch (IOException e) { e.printStackTrace(); } return JSONObject.parseObject(getStr).getJSONArray("data"); } public static JSONArray executeHttpGetResultArr(PlatformUrlEnum url, Map<String,String> paramsMap){ System.out.println(url); String getStr = null; try { getStr = postPayMsg(PlatformServerConfig.baseUrl+url.getUrl(),paramsMap); } catch (IOException e) { e.printStackTrace(); } return JSONObject.parseObject(getStr).getJSONArray("data"); } public static void executeHttpNoReturn(String url,Map<String,String> paramsMap){ System.out.println(url); String getStr = null; try { getStr = get(url,paramsMap); } catch (IOException e) { e.printStackTrace(); } //JSONObject jsonObject = JSONObject.parseObject(getStr); } /** * @描述: 执行返回JSON * @参数: [utl, paramsMap] * @返回值: java.lang.String * @创建人 WZQ * @创建时间: 17:17 2019/4/2 */ public static JSONObject executeHttpGetResult(String url,Map<String,String> paramsMap){ System.out.println(url); String getStr = null; try { getStr = get(url,paramsMap); } catch (IOException e) { e.printStackTrace(); } JSONObject jsonObject = JSONObject.parseObject(getStr); return jsonObject.getJSONObject("data"); } public static JSONObject executeHttpGetResult(PlatformUrlEnum url, Map<String,String> paramsMap){ System.out.println(url); String getStr = null; try { getStr = get(PlatformServerConfig.baseUrl+url.getUrl(),paramsMap); } catch (IOException e) { e.printStackTrace(); } return JSONObject.parseObject(getStr).getJSONObject("data"); } /** * @描述: * @参数: [url, paramsMap] * @返回值: com.alibaba.fastjson.JSONObject * @创建人 WZQ * @创建时间: 15:44 2019/4/8 */ /* public static JSONObject execute(String url,Map<String,String> paramsMap){ System.out.println(url); String getStr = null; try { getStr = get(url,paramsMap); } catch (IOException e) { e.printStackTrace(); } return JSONObject.parseObject(getStr); } */ /** * @描述: 执行获取Id * @参数: [url, paramsMap] * @返回值: java.lang.Long * @创建人 WZQ * @创建时间: 17:24 2019/4/2 */ public static Long executeHttpGetId(String url,Map<String,String> paramsMap){ Map<String,Object> tempMap = EncryptionConstants.encryptionConstantsMap.get(url); Method method = (Method) tempMap.get("method"); Object obj = tempMap.get("object"); List params = Lists.newArrayList(); for(String key : paramsMap.keySet()){ String value = paramsMap.get(key); if(value!=null&&(key.toLowerCase().equals("id")||key.toLowerCase().equals("indexid"))){ Long tempVal = Long.valueOf(value); params.add(tempVal); }else{ if("null".equals(value)){ params.add(null); }else{ params.add(value); } } } Object object = null; try { /*LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer(); String[] params1 = u.getParameterNames(method); String name = method.getParameters()[0].getName();*/ object = method.invoke(obj,params.toArray()); } catch (Exception e) { e.printStackTrace(); MeenoAssert.notTrue(true,"加密数据发生错误!"); } return ((JSONObject)object).getLong("id"); } /** * @描述: 执行返回JSON * @参数: [utl, paramsMap] * @返回值: java.lang.String * @创建人 WZQ * @创建时间: 17:17 2019/4/2 */ public static JSONObject executeHttp(String url,Map<String,String> paramsMap){ Map<String,Object> tempMap = EncryptionConstants.encryptionConstantsMap.get(url); Method method = (Method) tempMap.get("method"); Object obj = tempMap.get("object"); List params = Lists.newArrayList(); for(String key : paramsMap.keySet()){ String value = paramsMap.get(key); if(value!=null&&(key.toLowerCase().equals("id")||key.toLowerCase().equals("indexid"))){ Long tempVal = Long.valueOf(value); params.add(tempVal); }else{ if("null".equals(value)){ params.add(null); }else{ params.add(value); } } } Object object = null; try { object = method.invoke(obj,params.toArray()); } catch (Exception e) { e.printStackTrace(); MeenoAssert.notTrue(true,"加密数据发生错误!"); } return ((JSONObject)object); } /** * @描述: * @参数: [url, paramsMap] * @返回值: com.alibaba.fastjson.JSONObject * @创建人 WZQ * @创建时间: 15:44 2019/4/8 */ public static JSONObject execute(String url,Map<String,String> paramsMap){ Map<String,Object> tempMap = EncryptionConstants.encryptionConstantsMap.get(url); Method method = (Method) tempMap.get("method"); Object obj = tempMap.get("object"); List params = Lists.newArrayList(); for(String key : paramsMap.keySet()){ String value = paramsMap.get(key); if(value!=null&&(key.toLowerCase().equals("id")||key.toLowerCase().equals("indexid"))){ Long tempVal = Long.valueOf(value); params.add(tempVal); }else{ if("null".equals(value)){ params.add(null); }else{ params.add(value); } } } Object object = null; try { object = method.invoke(obj,params.toArray()); } catch (Exception e) { e.printStackTrace(); MeenoAssert.notTrue(true,"加密数据发生错误!"); } return ((JSONObject)object); } }
VideoUtils.java
videoUtils获取视频信息工具类
package com.meeno.wzq.alibaba.video; import com.google.common.collect.Maps; import com.meeno.framework.util.HttpUtils; import com.meeno.wzq.alibaba.signature.SignatureUtils; import java.io.IOException; import java.util.List; import java.util.Map; /** * @description: videoUtils获取视频信息工具类 * @author: Wzq * @create: 2020-01-14 19:31 */ public class VideoUtils { /** *@Description 获取签名结果 *@Param [accessKeyId, accessKeySecret, videoId] *@Return java.lang.String *@Author Wzq *@Date 2020/1/14 *@Time 19:30 */ public static String getVideoInfo(String accessKeyId,String accessKeySecret,String videoId) throws IOException { String timestamp = SignatureUtils.generateTimestamp(); String signatureNonce = SignatureUtils.generateRandom(); //1.1. 构造规范化的请求字符串 Map<String, String> privateParams = Maps.newLinkedHashMap(); privateParams.put("Action","GetVideoInfo"); privateParams.put("VideoId", videoId); Map<String, String> publicParams = Maps.newLinkedHashMap(); publicParams.put("Timestamp",timestamp); publicParams.put("Format","JSON"); publicParams.put("AccessKeyId",accessKeyId); publicParams.put("SignatureMethod", "HMAC-SHA1"); publicParams.put("SignatureNonce",signatureNonce); publicParams.put("Version", "2017-03-21"); publicParams.put("SignatureVersion","1.0"); List<String> allParams = SignatureUtils.getAllParams(publicParams, privateParams); String canonicalizedQueryString = SignatureUtils.getCQS(allParams); //1.2. 构造待签名的字符串 /*构造待签名的字符串*/ String StringToSign = "GET" + "&" + SignatureUtils.percentEncode("/") + "&" + SignatureUtils.percentEncode(canonicalizedQueryString); //1.3. 计算待签名字符串的HMAC值 byte[] bytes = SignatureUtils.hmacSHA1Signature(accessKeySecret, StringToSign); //1.4. 编码得到最终签名值 //按照 Base64 编码规则将1.3中计算得到的HMAC值编码成字符串,得到最终签名值(Signature)。 String signature = SignatureUtils.newStringByBase64(bytes); // log.info("-------------"+signature); Map<String,String> videoInfoMap = Maps.newLinkedHashMap(); videoInfoMap.put("Action","GetVideoInfo"); videoInfoMap.put("VideoId", videoId); videoInfoMap.put("Format","JSON"); videoInfoMap.put("AccessKeyId",accessKeyId); videoInfoMap.put("Signature",signature); videoInfoMap.put("SignatureMethod","HMAC-SHA1"); videoInfoMap.put("SignatureVersion","1.0"); videoInfoMap.put("SignatureNonce",signatureNonce); videoInfoMap.put("Timestamp", timestamp); videoInfoMap.put("Version","2017-03-21"); //调用http get请求 String resultStr = HttpUtils.getAjax("http://vod.cn-shanghai.aliyuncs.com", videoInfoMap); // log.info(s); return resultStr; } }
controller层代码如下:
/** *@Description 获取视频点播的视频信息 *@Param [session, request, response, data] *@Return void *@Author Wzq *@Date 2020/1/14 *@Time 19:34 */ @RequestMapping(value = "getVideoInfo.action") public void getVideoInfo(final HttpSession session, final HttpServletRequest request, final HttpServletResponse response, @RequestParam(value = "Data") String data) throws IOException { JSONObject jsonObject = JSONObject.parseObject(data); //视频点播videoId String videoId = jsonObject.getString("videoId"); Bank indexBank = this.enterpriseDao.getEnterprise().getIndexBank(); String accessKeyId = ""; String accessKeySecret = ""; String videoInfo = VideoUtils.getVideoInfo(accessKeyId, accessKeySecret, videoId); JSONObject resultJson = null; if(videoInfo != null && !videoInfo.isEmpty()){ resultJson = JSONObject.parseObject(videoInfo); } CommonUtil.toJson(response, new ResponseBean(Constant.RESPONSE_SUCCESS,"",resultJson)); }
个人微信公众,经常更新一些实用的干货:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。