diff --git a/build.gradle b/build.gradle index 20a3b60..89864c5 100644 --- a/build.gradle +++ b/build.gradle @@ -1,19 +1,28 @@ -plugins { - id 'java' -} +// Top-level build file where you can add configuration options common to all sub-projects/modules. + +buildscript { + repositories { + google() + jcenter() -group 'com.zl' -version '1.0-SNAPSHOT' + } + dependencies { + classpath 'com.android.tools.build:gradle:3.5.0' + classpath 'com.github.dcendents:android-maven-gradle-plugin:2.1' + + // NOTE: Do not place your application dependencies here; they belong + // in the individual module build.gradle files + } +} -sourceCompatibility = 1.8 +allprojects { + repositories { + google() + jcenter() -repositories { - mavenCentral() + } } -dependencies { - compile group: 'commons-codec', name: 'commons-codec', version: '1.13' - compile group: 'com.alibaba', name: 'fastjson', version: '1.2.59' - compile group: 'com.squareup.okhttp3', name: 'okhttp', version: '3.14.2' - testCompile group: 'junit', name: 'junit', version: '4.12' +task clean(type: Delete) { + delete rootProject.buildDir } diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 94336fc..f6b961f 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 96568ed..204df11 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ -#Mon Sep 02 17:26:07 CST 2019 +#Thu Aug 22 15:45:19 CST 2019 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-5.6-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-all.zip diff --git a/settings.gradle b/settings.gradle index 13f07e4..97195ca 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1,2 +1 @@ -rootProject.name = 'aliyun' - +include ':app', ':FaceDetect' diff --git a/src/main/java/com/zl/aliyun/iot/IotApi.java b/src/main/java/com/zl/aliyun/iot/IotApi.java deleted file mode 100644 index 005ae86..0000000 --- a/src/main/java/com/zl/aliyun/iot/IotApi.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.zl.aliyun.iot; - -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; -import java.util.HashMap; -import java.util.Map; - -/** - * @author ZL @朱林 - * @Version 1.0 - * @Description TODO - * @date 2019/09/02 17:40 - */ -public class IotApi { - // AccessKey 信息 - public static String accessKey = "1234567890123456"; - public static String accessKeySecret = "123456789012345678901234567890"; - - public final static String CHARSET_UTF8 = "utf8"; - - /** - * @param args - * @throws UnsupportedEncodingException - * @1. 需求修改Config.java中的AccessKey信息 - * @2. 建议使用方法二,所有参数都需要一一填写 - * @3. "最终signature"才是你需要的签名最终结果 - */ - public static void main(String[] args) throws UnsupportedEncodingException { - - // 方法一 - System.out.println("方法一:"); - String str = "GET&%2F&AccessKeyId%3D" + accessKey - + "%26Action%3DRegisterDevice%26DeviceName%3D1533023037%26Format%3DJSON%26ProductKey%3DaxxxUtgaRLB%26RegionId%3Dcn-shanghai%26SignatureMethod%3DHMAC-SHA1%26SignatureNonce%3D1533023037%26SignatureVersion%3D1" - + ".0%26Timestamp%3D2018-07-31T07%253A43%253A57Z%26Version%3D2018-01-20"; - byte[] signBytes; - try { - signBytes = SignatureUtils.hmacSHA1Signature(accessKeySecret + "&", str.toString()); - String signature = SignatureUtils.newStringByBase64(signBytes); - System.out.println("signString---" + str); - System.out.println("signature----" + signature); - System.out.println("最终signature:" + URLEncoder.encode(signature, CHARSET_UTF8)); - } catch (Exception e) { - e.printStackTrace(); - } - System.out.println(); - - // 方法二 - System.out.println("方法二:"); - Map map = new HashMap(); - // 公共参数 - map.put("Format", "JSON"); - map.put("Version", "2018-01-20"); - map.put("AccessKeyId", accessKey); - map.put("SignatureMethod", "HMAC-SHA1"); - map.put("Timestamp", "2018-07-31T07:43:57Z"); - map.put("SignatureVersion", "1.0"); - map.put("SignatureNonce", "1533023037"); - map.put("RegionId", "cn-shanghai"); - // 请求参数 - map.put("Action", "RegisterDevice"); - map.put("DeviceName", "1533023037"); - map.put("ProductKey", "axxxUtgaRLB"); - try { - String signature = SignatureUtils.generate("GET", map, accessKeySecret); - System.out.println("最终signature:" + signature); - } catch (Exception e) { - e.printStackTrace(); - } - System.out.println(); - } -} diff --git a/src/main/java/com/zl/aliyun/iot/SignatureUtils.java b/src/main/java/com/zl/aliyun/iot/SignatureUtils.java deleted file mode 100644 index ee29c15..0000000 --- a/src/main/java/com/zl/aliyun/iot/SignatureUtils.java +++ /dev/null @@ -1,100 +0,0 @@ -package com.zl.aliyun.iot; - -import com.zl.aliyun.util.StringUtil; -import org.apache.commons.codec.binary.Base64; - -import javax.crypto.Mac; -import javax.crypto.spec.SecretKeySpec; -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URLDecoder; -import java.net.URLEncoder; -import java.util.Map; -import java.util.TreeMap; - -/** - * @author ZL @朱林 - * @Version 1.0 - * @Description TODO - * @date 2019/09/02 17:40 - */ -public class SignatureUtils { - private final static String CHARSET_UTF8 = "utf8"; - private final static String ALGORITHM = "UTF-8"; - private final static String SEPARATOR = "&"; - - public static Map splitQueryString(String url) - throws URISyntaxException, UnsupportedEncodingException { - URI uri = new URI(url); - String query = uri.getQuery(); - final String[] pairs = query.split("&"); - TreeMap queryMap = new TreeMap(); - for (String pair : pairs) { - final int idx = pair.indexOf("="); - final String key = idx > 0 ? pair.substring(0, idx) : pair; - if (!queryMap.containsKey(key)) { - queryMap.put(key, URLDecoder.decode(pair.substring(idx + 1), CHARSET_UTF8)); - } - } - return queryMap; - } - - public static String generate(String method, Map parameter, String accessKeySecret) - throws Exception { - String signString = generateSignString(method, parameter); - System.out.println("signString---" + signString); - byte[] signBytes = hmacSHA1Signature(accessKeySecret + "&", signString); - String signature = newStringByBase64(signBytes); - System.out.println("signature----" + signature); - if ("POST".equals(method)) { - return signature; - } - return URLEncoder.encode(signature, "UTF-8"); - } - - public static String generateSignString(String httpMethod, Map parameter) throws IOException { - TreeMap sortParameter = new TreeMap(); - sortParameter.putAll(parameter); - String canonicalizedQueryString = UrlUtil.generateQueryString(sortParameter, true); - if (null == httpMethod) { - throw new RuntimeException("httpMethod can not be empty"); - } - StringBuilder stringToSign = new StringBuilder(); - stringToSign.append(httpMethod).append(SEPARATOR); - stringToSign.append(percentEncode("/")).append(SEPARATOR); - stringToSign.append(percentEncode(canonicalizedQueryString)); - return stringToSign.toString(); - } - - public static String percentEncode(String value) { - try { - return value == null ? null - : URLEncoder.encode(value, CHARSET_UTF8).replace("+", "%20").replace("*", "%2A").replace("%7E", - "~"); - } catch (Exception e) { - } - return ""; - } - - public static byte[] hmacSHA1Signature(String secret, String baseString) throws Exception { - if (StringUtil.isEmpty(secret)) { - throw new IOException("secret can not be empty"); - } - if (StringUtil.isEmpty(baseString)) { - return null; - } - Mac mac = Mac.getInstance("HmacSHA1"); - SecretKeySpec keySpec = new SecretKeySpec(secret.getBytes(CHARSET_UTF8), ALGORITHM); - mac.init(keySpec); - return mac.doFinal(baseString.getBytes(CHARSET_UTF8)); - } - - public static String newStringByBase64(byte[] bytes) throws UnsupportedEncodingException { - if (bytes == null || bytes.length == 0) { - return null; - } - return new String(Base64.encodeBase64(bytes, false), CHARSET_UTF8); - } -} diff --git a/src/main/java/com/zl/aliyun/iot/UrlUtil.java b/src/main/java/com/zl/aliyun/iot/UrlUtil.java deleted file mode 100644 index 3721b54..0000000 --- a/src/main/java/com/zl/aliyun/iot/UrlUtil.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.zl.aliyun.iot; - -import com.zl.aliyun.util.StringUtil; - -import java.net.URLEncoder; -import java.util.Map; - -/** - * @author ZL @朱林 - * @Version 1.0 - * @Description TODO - * @date 2019/09/02 17:43 - */ -public class UrlUtil { - private final static String CHARSET_UTF8 = "utf8"; - - public static String urlEncode(String url) { - if (!StringUtil.isEmpty(url)) { - try { - url = URLEncoder.encode(url, "UTF-8"); - } catch (Exception e) { - System.out.println("Url encode error:" + e.getMessage()); - } - } - return url; - } - - public static String generateQueryString(Map params, boolean isEncodeKV) { - StringBuilder canonicalizedQueryString = new StringBuilder(); - for (Map.Entry entry : params.entrySet()) { - if (isEncodeKV) { - canonicalizedQueryString.append(percentEncode(entry.getKey())).append("=") - .append(percentEncode(entry.getValue())).append("&"); - } else { canonicalizedQueryString.append(entry.getKey()).append("=").append(entry.getValue()).append("&"); } - } - if (canonicalizedQueryString.length() > 1) { - canonicalizedQueryString.setLength(canonicalizedQueryString.length() - 1); - } - return canonicalizedQueryString.toString(); - } - - public static String percentEncode(String value) { - try { - return value == null ? null : URLEncoder.encode(value, CHARSET_UTF8).replace("+", "%20").replace("*", "%2A").replace("%7E", "~"); - } catch (Exception e) { - - } - return ""; - } -} diff --git a/src/main/java/com/zl/aliyun/nls/CreateToekn.java b/src/main/java/com/zl/aliyun/nls/CreateToekn.java deleted file mode 100644 index 535c9a5..0000000 --- a/src/main/java/com/zl/aliyun/nls/CreateToekn.java +++ /dev/null @@ -1,244 +0,0 @@ -package com.zl.aliyun.nls; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; -import com.zl.aliyun.util.Base64Encoder; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; - -import javax.crypto.Mac; -import javax.crypto.spec.SecretKeySpec; -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.text.SimpleDateFormat; -import java.util.*; - -/** - * @author ZL @朱林 - * @Version 1.0 - * @Description TODO - * @date 2019/09/02 17:38 - */ -public class CreateToekn { - private final static String TIME_ZONE = "GMT"; - private final static String FORMAT_ISO8601 = "yyyy-MM-dd'T'HH:mm:ss'Z'"; - private final static String URL_ENCODING = "UTF-8"; - private static final String ALGORITHM_NAME = "HmacSHA1"; - private static final String ENCODING = "UTF-8"; - private static String token = null; - private static long expireTime = 0; - - /** - * 获取时间戳 - * 必须符合ISO8601规范,并需要使用UTC时间,时区为+0 - */ - public static String getISO8601Time(Date date) { - Date nowDate = date; - if (null == date) { - nowDate = new Date(); - } - SimpleDateFormat df = new SimpleDateFormat(FORMAT_ISO8601); - df.setTimeZone(new SimpleTimeZone(0, TIME_ZONE)); - return df.format(nowDate); - } - - /** - * 获取UUID - */ - public static String getUniqueNonce() { - UUID uuid = UUID.randomUUID(); - return uuid.toString(); - } - - /** - * URL编码 - * 使用UTF-8字符集按照 RFC3986 规则编码请求参数和参数取值 - */ - public static String percentEncode(String value) throws UnsupportedEncodingException { - return value != null ? URLEncoder.encode(value, URL_ENCODING).replace("+", "%20") - .replace("*", "%2A").replace("%7E", "~") : null; - } - - /*** - * 将参数排序后,进行规范化设置,组合成请求字符串 - * @param queryParamsMap 所有请求参数 - * @return 规范化的请求字符串 - */ - public static String canonicalizedQuery(Map queryParamsMap) { - String[] sortedKeys = queryParamsMap.keySet().toArray(new String[]{}); - Arrays.sort(sortedKeys); - String queryString = null; - try { - StringBuilder canonicalizedQueryString = new StringBuilder(); - for (String key : sortedKeys) { - canonicalizedQueryString.append("&") - .append(percentEncode(key)).append("=") - .append(percentEncode(queryParamsMap.get(key))); - } - queryString = canonicalizedQueryString.toString().substring(1); - System.out.println("规范化后的请求参数串:" + queryString); - } catch (UnsupportedEncodingException e) { - System.out.println("UTF-8 encoding is not supported."); - e.printStackTrace(); - } - return queryString; - } - - /*** - * 构造签名字符串 - * @param method HTTP请求的方法 - * @param urlPath HTTP请求的资源路径 - * @param queryString 规范化的请求字符串 - * @return 签名字符串 - */ - public static String createStringToSign(String method, String urlPath, String queryString) { - String stringToSign = null; - try { - StringBuilder strBuilderSign = new StringBuilder(); - strBuilderSign.append(method); - strBuilderSign.append("&"); - strBuilderSign.append(percentEncode(urlPath)); - strBuilderSign.append("&"); - strBuilderSign.append(percentEncode(queryString)); - stringToSign = strBuilderSign.toString(); - System.out.println("构造的签名字符串:" + stringToSign); - } catch (UnsupportedEncodingException e) { - System.out.println("UTF-8 encoding is not supported."); - e.printStackTrace(); - } - return stringToSign; - } - - /*** - * 计算签名 - * @param stringToSign 签名字符串 - * @param accessKeySecret 阿里云AccessKey Secret加上与号& - * @return 计算得到的签名 - */ - public static String sign(String stringToSign, String accessKeySecret) { - try { - Mac mac = Mac.getInstance(ALGORITHM_NAME); - mac.init(new SecretKeySpec( - accessKeySecret.getBytes(ENCODING), - ALGORITHM_NAME - )); - byte[] signData = mac.doFinal(stringToSign.getBytes(ENCODING)); - // String signBase64 = DatatypeConverter.printBase64Binary(signData); - // String signBase64= Base64.getEncoder().encodeToString(signData); - // String signBase64= android.util.Base64.encodeToString(signData, Base64.CRLF); - String signBase64= Base64Encoder.encode(signData); - System.out.println("计算的得到的签名:" + signBase64); - String signUrlEncode = percentEncode(signBase64); - System.out.println("UrlEncode编码后的签名:" + signUrlEncode); - return signUrlEncode; - } catch (NoSuchAlgorithmException e) { - throw new IllegalArgumentException(e.toString()); - } catch (UnsupportedEncodingException e) { - throw new IllegalArgumentException(e.toString()); - } catch (InvalidKeyException e) { - throw new IllegalArgumentException(e.toString()); - } - } - - /*** - * 发送HTTP GET请求,获取token和有效期时间戳 - * @param queryString 请求参数 - */ - public static void processGETRequest(String queryString) { - /** - * 设置HTTP GET请求 - * 1. 使用HTTP协议 - * 2. Token服务域名:nls-meta.cn-shanghai.aliyuncs.com - * 3. 请求路径:/ - * 4. 设置请求参数 - */ - String url = "http://nls-meta.cn-shanghai.aliyuncs.com"; - url = url + "/"; - url = url + "?" + queryString; - System.out.println("HTTP请求链接:" + url); - Request request = new Request.Builder() - .url(url) - .header("Accept", "application/json") - .get() - .build(); - try { - OkHttpClient client = new OkHttpClient(); - Response response = client.newCall(request).execute(); - String result = response.body().string(); - if (response.isSuccessful()) { - JSONObject rootObj = JSON.parseObject(result); - JSONObject tokenObj = rootObj.getJSONObject("Token"); - if (tokenObj != null) { - token = tokenObj.getString("Id"); - expireTime = tokenObj.getLongValue("ExpireTime"); - } else { - System.err.println("提交获取Token请求失败: " + result); - } - } else { - System.err.println("提交获取Token请求失败: " + result); - } - response.close(); - } catch (Exception e) { - e.printStackTrace(); - } - } - - public static void getToken(String accessKeyId, String accessKeySecret) { - System.out.println(getISO8601Time(null)); - // 所有请求参数 - Map queryParamsMap = new HashMap<>(); - queryParamsMap.put("AccessKeyId", accessKeyId); - queryParamsMap.put("Action", "CreateToken"); - queryParamsMap.put("Version", "2019-02-28"); - queryParamsMap.put("Timestamp", getISO8601Time(null)); - queryParamsMap.put("Format", "JSON"); - queryParamsMap.put("RegionId", "cn-shanghai"); - queryParamsMap.put("SignatureMethod", "HMAC-SHA1"); - queryParamsMap.put("SignatureVersion", "1.0"); - queryParamsMap.put("SignatureNonce", getUniqueNonce()); - /** - * 1.构造规范化的请求字符串 - */ - String queryString = canonicalizedQuery(queryParamsMap); - if (null == queryString) { - System.out.println("构造规范化的请求字符串失败!"); - return; - } - /** - * 2.构造签名字符串 - */ - String method = "GET"; // 发送请求的 HTTP 方法,GET - String urlPath = "/"; // 请求路径 - String stringToSign = createStringToSign(method, urlPath, queryString); - if (null == stringToSign) { - System.out.println("构造签名字符串失败"); - return; - } - /** - * 3.计算签名 - */ - String signature = sign(stringToSign, accessKeySecret + "&"); - if (null == signature) { - System.out.println("计算签名失败!"); - return; - } - /** - * 4.将签名加入到第1步获取的请求字符串 - */ - String queryStringWithSign = "Signature=" + signature + "&" + queryString; - System.out.println("带有签名的请求字符串:" + queryStringWithSign); - /** - * 5.发送HTTP GET请求,获取token - */ - processGETRequest(queryStringWithSign); - if (token != null) { - System.out.println("获取的Token:" + token + ", 有效期时间戳(秒):" + expireTime); - // 将10位数的时间戳转换为北京时间 - String expireDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(expireTime * 1000)); - System.out.println("Token有效期的北京时间:" + expireDate); - } - } -} diff --git a/src/main/java/com/zl/aliyun/nls/NlsToken.java b/src/main/java/com/zl/aliyun/nls/NlsToken.java deleted file mode 100644 index 22d1adb..0000000 --- a/src/main/java/com/zl/aliyun/nls/NlsToken.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.zl.aliyun.nls; - -import java.io.Serializable; - -/** - * @author ZL @朱林 - * @Version 1.0 - * @Description TODO - * @date 2019/09/03 16:19 - */ -public class NlsToken implements Serializable { - private static final long serialVersionUID = -841117051816861042L; - private long ExpireTime; - private String Id; - private String UserId; - - public NlsToken() { - } - - public long getExpireTime() { - return ExpireTime; - } - - public void setExpireTime(long expireTime) { - ExpireTime = expireTime; - } - - public String getId() { - return Id; - } - - public void setId(String id) { - Id = id; - } - - public String getUserId() { - return UserId; - } - - public void setUserId(String userId) { - UserId = userId; - } - - @Override - public String toString() { - return "NlsToken{" + - "ExpireTime=" + ExpireTime + - ", Id='" + Id + '\'' + - ", UserId='" + UserId + '\'' + - '}'; - } -} diff --git a/src/main/java/com/zl/aliyun/nls/NlsTokenResponse.java b/src/main/java/com/zl/aliyun/nls/NlsTokenResponse.java deleted file mode 100644 index d92532b..0000000 --- a/src/main/java/com/zl/aliyun/nls/NlsTokenResponse.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.zl.aliyun.nls; - -import java.io.Serializable; - -/** - * @author ZL @朱林 - * @Version 1.0 - * @Description TODO - * @date 2019/09/03 16:18 - */ -public class NlsTokenResponse implements Serializable { - private static final long serialVersionUID = 4564566096568781967L; - private String NlsRequestId; - private String RequestId; - private NlsToken Token; - - public NlsTokenResponse() { - } - - public String getNlsRequestId() { - return NlsRequestId; - } - - public void setNlsRequestId(String nlsRequestId) { - NlsRequestId = nlsRequestId; - } - - public String getRequestId() { - return RequestId; - } - - public void setRequestId(String requestId) { - RequestId = requestId; - } - - public NlsToken getToken() { - return Token; - } - - public void setToken(NlsToken token) { - Token = token; - } - - @Override - public String toString() { - return "NlsTokenResponse{" + - "NlsRequestId='" + NlsRequestId + '\'' + - ", RequestId='" + RequestId + '\'' + - ", Token=" + Token + - '}'; - } -} diff --git a/src/main/java/com/zl/aliyun/nls/TokenListener.java b/src/main/java/com/zl/aliyun/nls/TokenListener.java deleted file mode 100644 index 63cc310..0000000 --- a/src/main/java/com/zl/aliyun/nls/TokenListener.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.zl.aliyun.nls; - -/** - * @author ZL @朱林 - * @Version 1.0 - * @Description TODO - * @date 2019/09/04 16:18 - */ -public interface TokenListener { - /** - * 获取token成功 - * - * @param token - * @return - */ - void onSuccess(String token); - - /** - * 获取token失败 - * - * @param e - * @return - */ - void onError(Exception e); -} diff --git a/src/main/java/com/zl/aliyun/nls/TokenUtil.java b/src/main/java/com/zl/aliyun/nls/TokenUtil.java deleted file mode 100644 index 6892fd1..0000000 --- a/src/main/java/com/zl/aliyun/nls/TokenUtil.java +++ /dev/null @@ -1,150 +0,0 @@ -package com.zl.aliyun.nls; - -import com.alibaba.fastjson.TypeReference; -import com.zl.aliyun.util.DateUtil; -import com.zl.aliyun.util.SignUtil; -import com.zl.aliyun.util.StringUtil; -import com.zl.aliyun.util.UrlUtil; -import com.zl.aliyun.util.http.HttpCallBack; -import com.zl.aliyun.util.http.HttpUtil; - -import java.lang.ref.WeakReference; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; - -/** - * @author ZL @朱林 - * @Version 1.0 - * @Description TODO - * @date 2019/09/03 10:47 - */ -public class TokenUtil { - private static final String BASE_URL = "http://nls-meta.cn-shanghai.aliyuncs.com"; - private static TokenUtil INSTANCE; - private static WeakReference tokenReference; - - public TokenUtil() { - } - - public static String getToken(String accessKeyId, String accessKeySecret) { - String token = getMemberToken(); - if (StringUtil.isEmpty(token)) { - String queryString = generateTokenQuery(accessKeyId, accessKeySecret); - NlsToken nlsToken = synQueryToken(queryString); - if (nlsToken != null && !StringUtil.isEmpty(nlsToken.getId())) { - return nlsToken.getId(); - } else { - return null; - } - } else { - return token; - } - } - - public static void getToken(String accessKeyId, String accessKeySecret, TokenListener tokenListener) { - String token = getMemberToken(); - if (StringUtil.isEmpty(token)) { - String queryString = generateTokenQuery(accessKeyId, accessKeySecret); - aynQueryToken(queryString, tokenListener); - } else { - if (tokenListener != null) { - tokenListener.onSuccess(token); - } - } - } - - private static String getMemberToken() { - if (null == tokenReference) {return null;} - NlsToken nlsToken = tokenReference.get(); - if (null == nlsToken || StringUtil.isEmpty(nlsToken.getId())) {return null;} - Date tokenDate = new Date(nlsToken.getExpireTime() * 1000); - Date nowDate = new Date(System.currentTimeMillis()); - if (tokenDate.after(nowDate)) { - return nlsToken.getId(); - } else { - return null; - } - } - - private static void saveToken(NlsToken nlsToken) { - if (nlsToken != null) { - tokenReference = new WeakReference<>(nlsToken); - } - } - - public static String generateTokenQuery(String accessKeyId, String accessKeySecret) { - Map queryParamsMap = new HashMap<>(); - queryParamsMap.put("AccessKeyId", accessKeyId); - queryParamsMap.put("Action", "CreateToken"); - queryParamsMap.put("Version", "2019-02-28"); - queryParamsMap.put("Timestamp", DateUtil.getISO8601Time(null)); - queryParamsMap.put("Format", "JSON"); - queryParamsMap.put("RegionId", "cn-shanghai"); - queryParamsMap.put("SignatureMethod", "HMAC-SHA1"); - queryParamsMap.put("SignatureVersion", "1.0"); - queryParamsMap.put("SignatureNonce", SignUtil.getUniqueNonce()); - String queryString = UrlUtil.generateQueryString(queryParamsMap, true); - //System.out.println("规范化后的请求参数串:" + queryString); - if (null == queryString) { - //System.out.println("构造规范化的请求字符串失败!"); - return null; - } - String signString = SignUtil.generateHmacSHA1SignString("GET", "/", queryString); - //System.out.println("构造的签名字符串:" + signString); - if (null == signString) { - //System.out.println("构造签名字符串失败"); - return null; - } - String signature = SignUtil.hmacSHA1Sign(accessKeySecret + "&", signString); - //System.out.println("计算的得到的签名:" + signature); - if (null == signature) { - //System.out.println("计算签名失败!"); - return null; - } - /** - * 4.将签名加入到第1步获取的请求字符串 - */ - String queryStringWithSign = "Signature=" + signature + "&" + queryString; - //System.out.println("带有签名的请求字符串:" + queryStringWithSign); - return queryStringWithSign; - } - - public static NlsToken synQueryToken(String queryString) { - String url = BASE_URL + "/" + "?" + queryString; - HashMap headers = new HashMap<>(1); - headers.put("Accept", "application/json"); - NlsTokenResponse tokenResponse = HttpUtil.doGet(url, null, headers, new TypeReference() {}); - if (tokenResponse != null && tokenResponse.getToken() != null) { - saveToken(tokenResponse.getToken()); - return tokenResponse.getToken(); - } else { - return null; - } - } - - public static void aynQueryToken(String queryString, TokenListener tokenListener) { - String url = BASE_URL + "/" + "?" + queryString; - HashMap headers = new HashMap<>(1); - headers.put("Accept", "application/json"); - HttpUtil.doGet(url, null, headers, new HttpCallBack() { - @Override - public void onSuccess(NlsTokenResponse data) { - if (data != null && data.getToken() != null) { - saveToken(data.getToken()); - if (tokenListener != null) { - tokenListener.onSuccess(data.getToken().getId()); - } - } - } - - @Override - public void onException(Exception e) { - if (tokenListener != null) { - tokenListener.onError(e); - } - } - }); - } - -} diff --git a/src/main/java/com/zl/aliyun/util/Base64Encoder.java b/src/main/java/com/zl/aliyun/util/Base64Encoder.java deleted file mode 100644 index 342a364..0000000 --- a/src/main/java/com/zl/aliyun/util/Base64Encoder.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.zl.aliyun.util; - -/** - * @author ZL @朱林 - * @Version 1.0 - * @Description TODO - * @date 2019/09/02 17:38 - */ -public class Base64Encoder { - private static final char last2byte = (char) Integer - .parseInt("00000011", 2); - private static final char last4byte = (char) Integer - .parseInt("00001111", 2); - private static final char last6byte = (char) Integer - .parseInt("00111111", 2); - private static final char lead6byte = (char) Integer - .parseInt("11111100", 2); - private static final char lead4byte = (char) Integer - .parseInt("11110000", 2); - private static final char lead2byte = (char) Integer - .parseInt("11000000", 2); - private static final char[] encodeTable = new char[]{'A', 'B', 'C', 'D', - 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', - 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', - 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', - 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', - '4', '5', '6', '7', '8', '9', '+', '/'}; - - /** - * Base64 encoding. - * - * @param from The src data. - * @return - */ - public static String encode(byte[] from) { - StringBuffer to = new StringBuffer((int) (from.length * 1.34) + 3); - int num = 0; - char currentByte = 0; - for (int i = 0; i < from.length; i++) { - num = num % 8; - while (num < 8) { - switch (num) { - case 0: - currentByte = (char) (from[i] & lead6byte); - currentByte = (char) (currentByte >>> 2); - break; - case 2: - currentByte = (char) (from[i] & last6byte); - break; - case 4: - currentByte = (char) (from[i] & last4byte); - currentByte = (char) (currentByte << 2); - if ((i + 1) < from.length) { - currentByte |= (from[i + 1] & lead2byte) >>> 6; - } - break; - case 6: - currentByte = (char) (from[i] & last2byte); - currentByte = (char) (currentByte << 4); - if ((i + 1) < from.length) { - currentByte |= (from[i + 1] & lead4byte) >>> 4; - } - break; - } - to.append(encodeTable[currentByte]); - num += 6; - } - } - if (to.length() % 4 != 0) { - for (int i = 4 - to.length() % 4; i > 0; i--) { - to.append("="); - } - } - return to.toString(); - } -} diff --git a/src/main/java/com/zl/aliyun/util/DateUtil.java b/src/main/java/com/zl/aliyun/util/DateUtil.java deleted file mode 100644 index 6db23bf..0000000 --- a/src/main/java/com/zl/aliyun/util/DateUtil.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.zl.aliyun.util; - -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.SimpleTimeZone; - -/** - * @author ZL @朱林 - * @Version 1.0 - * @Description TODO - * @date 2019/09/02 17:49 - */ -public class DateUtil { - private final static String TIME_ZONE = "GMT"; - private final static String FORMAT_ISO8601 = "yyyy-MM-dd'T'HH:mm:ss'Z'"; - - /** - * 获取时间戳 - * 符合ISO8601规范,并需要使用UTC时间,时区为+0 - */ - public static String getISO8601Time(Date date) { - Date nowDate = date; - if (null == date) { - nowDate = new Date(); - } - SimpleDateFormat df = new SimpleDateFormat(FORMAT_ISO8601); - df.setTimeZone(new SimpleTimeZone(0, TIME_ZONE)); - return df.format(nowDate); - } -} diff --git a/src/main/java/com/zl/aliyun/util/JsonUtil.java b/src/main/java/com/zl/aliyun/util/JsonUtil.java deleted file mode 100644 index a213c3e..0000000 --- a/src/main/java/com/zl/aliyun/util/JsonUtil.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.zl.aliyun.util; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.TypeReference; - -import java.lang.reflect.Type; -import java.util.List; - -/** - * @author ZL @朱林 - * @Version 1.0 - * @Description JSON解析工具 - * @date 2019/09/02 11:21 - */ - -public class JsonUtil { - /** - * @param object 类的实例 - * @return JSON字符串 - */ - public static String toJson(Object object) { - if (null == object) { - return null; - } - return JSON.toJSONString(object); - } - - /** - * @param 泛型声明 - * @param json JSON字符串 - * @param clazz 要转换对象的类型 - * @return - */ - public static T fromJson(String json, Class clazz) { - if (null == json || json.length() <= 0) { return null; } - return JSON.parseObject(json, clazz); - } - - public static T fromJson(String json, TypeReference type) { - if (null == json || json.length() <= 0) { return null; } - return JSON.parseObject(json, type); - } - - public static T fromJson(String json, Type type) { - if (null == json || json.length() <= 0) { return null; } - return JSON.parseObject(json, type); - } - - /** - * 解析json使用泛型转换为对应List - * - * @return - */ - public static List json2List(String json, Class clazz) { - if (null == json || json.length() <= 0) { return null; } - return JSON.parseArray(json, clazz); - } - -} diff --git a/src/main/java/com/zl/aliyun/util/SignUtil.java b/src/main/java/com/zl/aliyun/util/SignUtil.java deleted file mode 100644 index c08bcf9..0000000 --- a/src/main/java/com/zl/aliyun/util/SignUtil.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.zl.aliyun.util; - -import javax.crypto.Mac; -import javax.crypto.spec.SecretKeySpec; -import java.io.IOException; -import java.util.Map; -import java.util.UUID; - -/** - * @author ZL @朱林 - * @Version 1.0 - * @Description TODO - * @date 2019/09/03 10:24 - */ -public class SignUtil { - private final static String CHARSET_UTF8 = "utf8"; - private final static String SEPARATOR = "&"; - private static final String ENCODING = "UTF-8"; - - /** - * 获取UUID - */ - public static String getUniqueNonce() { - UUID uuid = UUID.randomUUID(); - return uuid.toString(); - } - - public static String generateHmacSHA1SignString(String method, String urlPath, Map params) { - String queryString = UrlUtil.generateQueryString(params, true); - return generateHmacSHA1SignString(method, urlPath, queryString); - } - - public static String generateHmacSHA1SignString(String method, String urlPath, String queryString) { - StringBuilder strBuilderSign = new StringBuilder(); - strBuilderSign.append(method); - strBuilderSign.append(SEPARATOR); - strBuilderSign.append(UrlUtil.percentEncode(urlPath)); - strBuilderSign.append(SEPARATOR); - strBuilderSign.append(UrlUtil.percentEncode(queryString)); - return strBuilderSign.toString(); - } - - public static byte[] hmacSHA1Signature(String secret, String baseString) throws Exception { - if (StringUtil.isEmpty(secret)) { - throw new IOException("secret can not be empty"); - } - if (StringUtil.isEmpty(baseString)) { - return null; - } - Mac mac = Mac.getInstance("HmacSHA1"); - SecretKeySpec keySpec = new SecretKeySpec(secret.getBytes(CHARSET_UTF8), ENCODING); - mac.init(keySpec); - return mac.doFinal(baseString.getBytes(CHARSET_UTF8)); - } - - public static String hmacSHA1Sign(String secret, String baseString) { - try { - byte[] signData = hmacSHA1Signature(secret, baseString); - if (signData != null && signData.length > 0) { - return Base64Encoder.encode(signData); - } else { - return null; - } - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } - -} diff --git a/src/main/java/com/zl/aliyun/util/StringUtil.java b/src/main/java/com/zl/aliyun/util/StringUtil.java deleted file mode 100644 index 9c5609c..0000000 --- a/src/main/java/com/zl/aliyun/util/StringUtil.java +++ /dev/null @@ -1,234 +0,0 @@ -package com.zl.aliyun.util; - -import java.io.UnsupportedEncodingException; -import java.util.*; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * @author ZL @朱林 - * @Version 1.0 - * @Description TODO - * @date 2019/09/02 17:41 - */ -public class StringUtil { - - public static boolean isEmpty(String value) { - if (value != null && value.length() > 0) { - return false; - } - return true; - } - - public static List stringToSList(String data) { - return stringToSList(data, ","); - } - - public static List stringToSList(String data, String regex) { - if (isEmpty(data) || isEmpty(regex)) { - return null; - } - return new ArrayList<>(Arrays.asList(data.split(regex))); - } - - public static List stringToLList(String data) { - return stringToLList(data, ","); - } - - public static List stringToLList(String data, String regex) { - if (isEmpty(data) || isEmpty(regex)) { - return null; - } - String[] strings = data.split(regex); - List list = new ArrayList<>(); - for (String string : strings) { - Long values = stringToLong(string); - if (values != null) { - list.add(values); - } - } - return list; - } - - public static Integer stringToInteger(String data) { - Integer value = null; - try { - if (!isEmpty(data)) { - value = Integer.parseInt(data); - } - } catch (NumberFormatException e) { - e.printStackTrace(); - } - return value; - } - - public static Long stringToLong(String data) { - Long value = null; - try { - if (!isEmpty(data)) { - value = Long.parseLong(data); - } - } catch (NumberFormatException e) { - e.printStackTrace(); - } - return value; - } - - public static Double stringToDouble(String data) { - Double value = null; - try { - if (!isEmpty(data)) { - value = Double.parseDouble(data); - } - } catch (NumberFormatException e) { - e.printStackTrace(); - } - return value; - } - - public static String IntegerToString(Integer data) { - if (data != null) { - return String.valueOf(data); - } else { - return ""; - } - } - - public static String doubleToString(Double data) { - if (data == null) { return ""; } - - return doubleToString(data, "%.2f"); - } - - public static String doubleToString(Double data, String format) { - String value = null; - if (data != null) { - try { - value = String.format(format, data); - } catch (IllegalFormatException ex) { - ex.printStackTrace(); - } - } - if (isEmpty(value)) { - value = "0"; - } - return value; - } - - public static Boolean isNumeric(String str) { - if (null == str || str.length() == 0) { - return false; - } - for (int i = str.length(); --i >= 0; ) { - if (!Character.isDigit(str.charAt(i))) { - return false; - } - } - return true; - } - - public static String getRandNumberString() { - int min = 10000; - int max = 99999; - Random random = new Random(); - int randNumber = random.nextInt(max) % (max - min + 1) + min; - StringBuilder sb = new StringBuilder(); - sb.append(System.currentTimeMillis()); - sb.append(randNumber); - return sb.toString(); - } - - public static String join(List list, String split) { - if (null == list || list.size() == 0 || null == split) { - return null; - } - String strResult = ""; - StringBuilder stringBuilder = new StringBuilder(); - int splitLength = split.length(); - for (T tmp : list) { - stringBuilder.append(tmp); - stringBuilder.append(split); - } - strResult = stringBuilder.toString(); - strResult = strResult.substring(0, strResult.length() - splitLength); - return strResult; - } - - /** - * 字符串中批量替换某些字符 - * - * @param replacementDefine 要替换的定义,key为被替换掉的值,支持正则表达式;value为替换之后的值(value为$等正则字符时会报错) - * @param string 要检索替换的字符串主体 - * @return 替换之后的字符串 - * @throws IllegalStateException If no match has yet been attempted, or if the previous match operation failed - * @throws IllegalArgumentException If the replacement string refers to a named-capturing group that does not exist in the pattern - * @throws IndexOutOfBoundsException If the replacement string refers to a capturing group that does not exist in the pattern - */ - public static String batchReplace(Map replacementDefine, String string) { - if (null == replacementDefine || replacementDefine.size() == 0 || null == string || string.length() == 0) { - return ""; - } - Set defineKetSet = replacementDefine.keySet(); - String regex = "(" + StringUtil.join(new ArrayList<>(defineKetSet), ")|(") + ")"; - Map replaceMap = new HashMap<>(); - int keyCount = 1; - for (String key : defineKetSet) { - replaceMap.put(keyCount++, replacementDefine.get(key)); - } - return batchReplaceInString(regex, replaceMap, string); - } - - /** - * 内部使用替换核心,专服务于batchReplace,filterBadWord - * - * @param regex 替换的正则表达式 - * @param replaceMap 被替换的单元定义 - * @param string - * @return - */ - private static String batchReplaceInString(String regex, Map replaceMap, String string) { - Set replaceKeys = replaceMap.keySet(); - Matcher matcher = Pattern.compile(regex).matcher(string); - StringBuffer sb = new StringBuffer(); - while (matcher.find()) { - for (Integer intKey : replaceKeys) { - if (null != matcher.group(intKey)) { - matcher.appendReplacement(sb, replaceMap.get(intKey)); - } - } - } - matcher.appendTail(sb); - return sb.toString(); - } - - public static String getUrlStringValue(String name, String value) { - try { - return new String(value.getBytes("ISO-8859-1"), "UTF-8"); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - return null; - } - } - - public static String getUrlStringValue(String value) { - return getUrlStringValue("文本", value); - } - - public static List ids(String ids) { - String[] sids = ids.split(","); - List list = new ArrayList(); - for (String sid : sids) { - try { - list.add(Long.valueOf(sid)); - } catch (NumberFormatException ignored) { - - } - } - HashSet hs = new HashSet(list); - list.clear(); - for (Long h : hs) { - list.add(h); - } - return list; - } -} diff --git a/src/main/java/com/zl/aliyun/util/UrlUtil.java b/src/main/java/com/zl/aliyun/util/UrlUtil.java deleted file mode 100644 index 5e5a88b..0000000 --- a/src/main/java/com/zl/aliyun/util/UrlUtil.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.zl.aliyun.util; - -import java.net.URLEncoder; -import java.util.Arrays; -import java.util.Map; - -/** - * @author ZL @朱林 - * @Version 1.0 - * @Description TODO - * @date 2019/09/02 18:00 - */ -public class UrlUtil { - private final static String URL_ENCODING = "UTF-8"; - - /** - * URL编码 使用UTF-8字符集按照 RFC3986 规则编码请求参数和参数取值 - */ - public static String percentEncode(String value) { - try { - return value != null ? URLEncoder.encode(value, URL_ENCODING).replace("+", "%20") - .replace("*", "%2A").replace("%7E", "~") : null; - } catch (Exception ex) { - ex.printStackTrace(); - return null; - } - } - - public static String generateQueryString(Map params, boolean isEncode) { - if (null == params || params.size() < 1) {return null;} - String[] sortedKeys = params.keySet().toArray(new String[] {}); - Arrays.sort(sortedKeys); - StringBuilder queryBuilder = new StringBuilder(); - for (String key : sortedKeys) { - if (isEncode) { - queryBuilder.append(percentEncode(key)).append("=") - .append(percentEncode(params.get(key))).append("&"); - } else { - queryBuilder.append(key).append("=") - .append(params.get(key)).append("&"); - } - } - if (queryBuilder.length() > 1) { - queryBuilder.setLength(queryBuilder.length() - 1); - } - return queryBuilder.toString(); - } - - public static String urlEncode(String url) { - if (!StringUtil.isEmpty(url)) { - try { - url = URLEncoder.encode(url, URL_ENCODING); - } catch (Exception e) { - e.printStackTrace(); - } - } - return url; - } -} diff --git a/src/main/java/com/zl/aliyun/util/http/ByteContentFile.java b/src/main/java/com/zl/aliyun/util/http/ByteContentFile.java deleted file mode 100644 index 76046aa..0000000 --- a/src/main/java/com/zl/aliyun/util/http/ByteContentFile.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.zl.aliyun.util.http; - -import java.io.Serializable; - -/** - * @author ZL - */ -public final class ByteContentFile implements Serializable { - private static final long serialVersionUID = 127254956313902461L; - private String reqName; - private String fileName; - private byte[] content; - - public ByteContentFile() { - } - - public ByteContentFile(String reqName, String fileName, byte[] content) { - this.reqName = reqName; - this.fileName = fileName; - this.content = content; - } - - public String getReqName() { - return reqName; - } - - public void setReqName(String reqName) { - this.reqName = reqName; - } - - public String getFileName() { - return fileName; - } - - public void setFileName(String fileName) { - this.fileName = fileName; - } - - public byte[] getContent() { - return content; - } - - public void setContent(byte[] content) { - this.content = content; - } - - @Override - public String toString() { - return "ByteContentFile{" + - "reqName='" + reqName + '\'' + - ", fileName='" + fileName + '\'' + - ", content=" + content.length + - '}'; - } -} diff --git a/src/main/java/com/zl/aliyun/util/http/FileContentFile.java b/src/main/java/com/zl/aliyun/util/http/FileContentFile.java deleted file mode 100644 index 9f840b4..0000000 --- a/src/main/java/com/zl/aliyun/util/http/FileContentFile.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.zl.aliyun.util.http; - -import java.io.File; -import java.io.Serializable; - -/** - * @author zl - * @Version 1.0 - * @Description TODO - * @date 2018/11/02 10:21 - */ -public class FileContentFile implements Serializable { - private static final long serialVersionUID = -6339050941229672951L; - private String reqName; - private String fileName; - private File file; - - public FileContentFile() { - } - - public FileContentFile(String reqName, String fileName, File file) { - this.reqName = reqName; - this.fileName = fileName; - this.file = file; - } - - public String getReqName() { - return reqName; - } - - public void setReqName(String reqName) { - this.reqName = reqName; - } - - public String getFileName() { - return fileName; - } - - public void setFileName(String fileName) { - this.fileName = fileName; - } - - public File getFile() { - return file; - } - - public void setFile(File file) { - this.file = file; - } - - @Override - public String toString() { - return "FileContentFile{" + - "reqName='" + reqName + '\'' + - ", fileName='" + fileName + '\'' + - ", file=" + file.getAbsolutePath() + - '}'; - } -} diff --git a/src/main/java/com/zl/aliyun/util/http/HttpCallBack.java b/src/main/java/com/zl/aliyun/util/http/HttpCallBack.java deleted file mode 100644 index 17c7b8c..0000000 --- a/src/main/java/com/zl/aliyun/util/http/HttpCallBack.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.zl.aliyun.util.http; - -/** - * @author zl - * @Version 1.0 - * @Description TODO - * @date 2019/01/16 14:51 - */ -public interface HttpCallBack { - /** - * 网络请求成功 - * - * @param data - * @return - */ - void onSuccess(T data); - - /** - * 网络请求异常 - * - * @param e - * @return - */ - void onException(Exception e); -} diff --git a/src/main/java/com/zl/aliyun/util/http/HttpUtil.java b/src/main/java/com/zl/aliyun/util/http/HttpUtil.java deleted file mode 100644 index 65d0b79..0000000 --- a/src/main/java/com/zl/aliyun/util/http/HttpUtil.java +++ /dev/null @@ -1,261 +0,0 @@ -package com.zl.aliyun.util.http; - -import com.alibaba.fastjson.TypeReference; -import com.zl.aliyun.util.JsonUtil; -import com.zl.aliyun.util.StringUtil; -import okhttp3.*; - -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.net.URLEncoder; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.TimeUnit; - -/** - * @author zl - * @Version 1.0 - * @Description TODO - * @date 2019/01/16 14:52 - */ -public class HttpUtil { - private static long TIMEOUT_WRITE = 20; - private static long TIMEOUT_READ = 20; - private static long TIMEOUT_CONNECT = 20; - - private volatile static OkHttpClient mClient; - - public static OkHttpClient getClient() { - if (null == mClient) { - synchronized (OkHttpClient.class) { - if (null == mClient) { - OkHttpClient.Builder builder = new OkHttpClient.Builder(); - builder.writeTimeout(TIMEOUT_WRITE, TimeUnit.SECONDS); - builder.readTimeout(TIMEOUT_READ, TimeUnit.SECONDS); - builder.connectTimeout(TIMEOUT_CONNECT, TimeUnit.SECONDS); - mClient = builder.build(); - } - } - } - return mClient; - } - - public static void setTimeoutWrite(long timeoutWrite) { - TIMEOUT_WRITE = timeoutWrite; - } - - public static void setTimeoutRead(long timeoutRead) { - TIMEOUT_READ = timeoutRead; - } - - public static void setTimeoutConnect(long timeoutConnect) { - TIMEOUT_CONNECT = timeoutConnect; - } - - public static void doGet(String url, Map params, Map headers, HttpCallBack callBack) { - String reqUrl = url; - if (params != null && params.size() > 0) { reqUrl = reqUrl + "?" + parseUrlRequest(params); } - Request.Builder builder = new Request.Builder(); - builder.url(reqUrl); - if (headers != null && headers.size() > 0) { builder.headers(getHeaders(headers)); } - request(builder.build(), callBack); - } - - public static T doGet(String url, Map params, Map headers, TypeReference type) { - String reqUrl = url; - if (params != null && params.size() > 0) { reqUrl = reqUrl + "?" + parseUrlRequest(params); } - Request.Builder builder = new Request.Builder(); - builder.url(reqUrl); - if (headers != null && headers.size() > 0) { builder.headers(getHeaders(headers)); } - return request(builder.build(), type); - } - - public static void doPost(String url, Map params, HttpCallBack callBack) { - requestPost(url, getBody(params), null, callBack); - } - - public static void doPostFile(String url, Map params, FileContentFile file, HttpCallBack callBack) { - requestPost(url, getBody(params, file), null, callBack); - } - - public static void doPostFile(String url, Map params, FileContentFile file, Map heardes, HttpCallBack callBack) { - requestPost(url, getBody(params, file), heardes, callBack); - } - - public static T doPost(String url, Map params, TypeReference type) { - return requestPost(url, getBody(params), null, type); - } - - public static T doPostJson(String url, Map params, TypeReference type) { - Map heardes = new HashMap<>(1); - heardes.put("content-type", "application/json;charset:utf-8"); - return requestPost(url, getBodyForJson(params), heardes, type); - } - - public static T doPostFile(String url, Map params, ByteContentFile file, TypeReference type) { - return requestPost(url, getBody(params, file), null, type); - } - - public static void doPostFile(String url, Map params, ByteContentFile file, HttpCallBack callBack) { - requestPost(url, getBody(params, file), null, callBack); - } - - public static T doPostFile(String url, Map params, FileContentFile file, TypeReference type) { - return requestPost(url, getBody(params, file), null, type); - } - - public static T doPostFile(String url, Map params, FileContentFile file, Map heardes, TypeReference type) { - return requestPost(url, getBody(params, file), heardes, type); - } - - public static void requestPost(String url, RequestBody body, Map headers, HttpCallBack callBack) { - Request.Builder builder = new Request.Builder(); - builder.url(url); - if (headers != null && headers.size() > 0) { builder.headers(getHeaders(headers)); } - builder.post(body); - request(builder.build(), callBack); - } - - public static T requestPost(String url, RequestBody body, Map headers, TypeReference type) { - Request.Builder builder = new Request.Builder(); - builder.url(url); - if (headers != null && headers.size() > 0) { builder.headers(getHeaders(headers)); } - builder.post(body); - return request(builder.build(), type); - } - - public static void request(Request request, final HttpCallBack callBack) { - getClient().newCall(request).enqueue(new Callback() { - @Override - public void onFailure(Call call, IOException e) { - if (callBack != null) { callBack.onException(e); } - } - - @Override - public void onResponse(Call call, Response response) throws IOException { - String result = response.body().string(); - if (!StringUtil.isEmpty(result)) { - if (callBack != null) { - try { - Type type = ((ParameterizedType)callBack.getClass().getGenericInterfaces()[0]).getActualTypeArguments()[0]; - callBack.onSuccess(JsonUtil.fromJson(result, type)); - } catch (Exception e) { - callBack.onException(e); - } - } - } - } - }); - } - - public static T request(Request request, TypeReference type) { - try { - Response response = getClient().newCall(request).execute(); - String result = response.body().string(); - System.out.println(result); - if (!StringUtil.isEmpty(result)) { - return JsonUtil.fromJson(result, type); - } - } catch ( - IOException e) { - e.printStackTrace(); - } - return null; - } - - public static Headers getHeaders(Map headers) { - Headers.Builder builder = new Headers.Builder(); - if (headers != null && headers.size() > 0) { - for (Map.Entry entry : headers.entrySet()) { - builder.add(entry.getKey(), urlEncoderUTF8(entry.getValue().toString())); - } - } - return builder.build(); - } - - public static RequestBody getBody(Map params) { - FormBody.Builder bodyBuilder = new FormBody.Builder(); - if (params != null && params.size() > 0) { - for (Map.Entry entry : params.entrySet()) { - bodyBuilder.add(entry.getKey(), urlEncoderUTF8(entry.getValue().toString())); - } - } - return bodyBuilder.build(); - } - - public static RequestBody getBodyForJson(Map params) { - String json = JsonUtil.toJson(params); - MediaType mediaType = MediaType.parse("application/json,charset=utf-8"); - RequestBody requestBody = RequestBody.create(mediaType, json); - return requestBody; - } - - public static RequestBody getBody(Map params, ByteContentFile file) { - MultipartBody.Builder bodyBuilder = new MultipartBody.Builder(); - bodyBuilder.setType(MultipartBody.FORM); - if (params != null && params.size() > 0) { - for (Map.Entry entry : params.entrySet()) { - bodyBuilder.addFormDataPart(entry.getKey(), urlEncoderUTF8(entry.getValue().toString())); - } - } - if (file != null && file.getContent() != null) { - bodyBuilder.addFormDataPart(file.getReqName(), file.getFileName(), RequestBody.create(MediaType.parse("application/octet-stream"), file.getContent())); - } - return bodyBuilder.build(); - } - - public static RequestBody getBody(Map params, FileContentFile file) { - MultipartBody.Builder bodyBuilder = new MultipartBody.Builder(); - bodyBuilder.setType(MultipartBody.FORM); - if (params != null && params.size() > 0) { - for (Map.Entry entry : params.entrySet()) { - bodyBuilder.addFormDataPart(entry.getKey(), urlEncoderUTF8(entry.getValue().toString())); - } - } - if (file != null && file.getFile() != null) { - bodyBuilder.addFormDataPart(file.getReqName(), file.getFileName(), RequestBody.create(MediaType.parse("application/octet-stream"), file.getFile())); - } - return bodyBuilder.build(); - } - - public static RequestBody getBody(Map params, List fileList) { - MultipartBody.Builder bodyBuilder = new MultipartBody.Builder(); - bodyBuilder.setType(MultipartBody.FORM); - if (params != null && params.size() > 0) { - for (Map.Entry entry : params.entrySet()) { - bodyBuilder.addFormDataPart(entry.getKey(), urlEncoderUTF8(entry.getValue().toString())); - } - } - if (fileList != null && fileList.size() > 0) { - for (FileContentFile fileContentFile : fileList) { - if (fileContentFile != null && fileContentFile.getFile() != null) { - bodyBuilder.addFormDataPart(fileContentFile.getReqName(), fileContentFile.getFileName(), RequestBody.create(MediaType.parse("application/octet-stream"), fileContentFile.getFile())); - } - } - } - return bodyBuilder.build(); - } - - public static String parseUrlRequest(Map params) { - StringBuffer buffer = new StringBuffer(); - if (params != null && params.size() > 0) { - for (Map.Entry entry : params.entrySet()) { - if (buffer.length() > 0) { buffer.append("&"); } - buffer.append(String.format("%s=%s", urlEncoderUTF8(entry.getKey()), urlEncoderUTF8(entry.getValue().toString()))); - } - } - return buffer.toString(); - } - - public static String urlEncoderUTF8(String s) { - try { - return URLEncoder.encode(s, "UTF-8"); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } - return s; - } -} diff --git a/src/test/java/com/zl/demo/nls/NLSDemo.java b/src/test/java/com/zl/demo/nls/NLSDemo.java deleted file mode 100644 index 8de49db..0000000 --- a/src/test/java/com/zl/demo/nls/NLSDemo.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.zl.demo.nls; - -import com.zl.aliyun.nls.TokenListener; -import com.zl.aliyun.nls.TokenUtil; -import org.junit.Test; - -import java.text.SimpleDateFormat; -import java.util.Date; - -/** - * @author ZL @朱林 - * @Version 1.0 - * @Description TODO - * @date 2019/09/03 16:26 - */ -public class NLSDemo { - private static final String accessKeyId = "LTAIQDnXhioZ6TJF"; - private static final String accessKeySecret = "njZGVbnrPph1dvW5ykMYgdFDO3WOBA"; - - @Test - public void testAsync() { - TokenUtil.getToken(accessKeyId, accessKeySecret, new TokenListener() { - @Override - public void onSuccess(String token) { - System.out.println("token:"+token); - } - - @Override - public void onError(Exception e) { - System.out.println("Exception:"+e); - } - }); - String token= TokenUtil.getToken(accessKeyId, accessKeySecret); - System.out.println("token:"+token); - } - @Test - public void testSync() { - String token= TokenUtil.getToken(accessKeyId, accessKeySecret); - System.out.println("token:"+token); - } - - @Test - public void testExpireTime(){ - long time=1567670678L; - Date date=new Date(time*1000); - SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - System.out.println(df.format(date)); - } -}