Commit 241d25d8ae6e34f412b03d774642ab6e6e013144

Authored by baishou
1 parent 598cc868
Exists in master

涂鸦云服务接口调用

springboot/pom.xml
... ... @@ -23,12 +23,12 @@
23 23 <dependency>
24 24 <groupId>org.springframework.boot</groupId>
25 25 <artifactId>spring-boot-starter-web</artifactId>
26   - <exclusions>
27   - <exclusion>
28   - <groupId>org.springframework.boot</groupId>
29   - <artifactId>spring-boot-starter-tomcat</artifactId>
30   - </exclusion>
31   - </exclusions>
  26 + <!--<exclusions>-->
  27 + <!--<exclusion>-->
  28 + <!--<groupId>org.springframework.boot</groupId>-->
  29 + <!--<artifactId>spring-boot-starter-tomcat</artifactId>-->
  30 + <!--</exclusion>-->
  31 + <!--</exclusions>-->
32 32 </dependency>
33 33  
34 34 <dependency>
... ... @@ -38,6 +38,12 @@
38 38  
39 39 <dependency>
40 40 <groupId>org.springframework.boot</groupId>
  41 + <artifactId>spring-boot-starter-tomcat</artifactId>
  42 + <scope>provided</scope>
  43 + </dependency>
  44 +
  45 + <dependency>
  46 + <groupId>org.springframework.boot</groupId>
41 47 <artifactId>spring-boot-starter-test</artifactId>
42 48 <scope>test</scope>
43 49 </dependency>
... ... @@ -70,6 +76,42 @@
70 76 <artifactId>mybatis-spring-boot-starter</artifactId>
71 77 <version>2.0.0</version>
72 78 </dependency>
  79 +
  80 + <!--模拟http请求包-->
  81 + <dependency>
  82 + <groupId>org.apache.httpcomponents</groupId>
  83 + <artifactId>httpclient</artifactId>
  84 + <version>4.5.3</version>
  85 + </dependency>
  86 +
  87 + <!--Json格式的字符串序列化和反序列化 jackson-->
  88 + <dependency>
  89 + <groupId>com.fasterxml.jackson.core</groupId>
  90 + <artifactId>jackson-databind</artifactId>
  91 + <version>2.9.8</version>
  92 + </dependency>
  93 + <!--Json格式的字符串序列化和反序列化 fastjson-->
  94 + <dependency>
  95 + <groupId>com.alibaba</groupId>
  96 + <artifactId>fastjson</artifactId>
  97 + <version>1.2.58</version>
  98 + </dependency>
  99 + <!--开启 cache 缓存-->
  100 + <dependency>
  101 + <groupId>org.springframework.boot</groupId>
  102 + <artifactId>spring-boot-starter-cache</artifactId>
  103 + </dependency>
  104 + <!-- ehcache 缓存 -->
  105 + <dependency>
  106 + <groupId>net.sf.ehcache</groupId>
  107 + <artifactId>ehcache</artifactId>
  108 + </dependency>
  109 +
  110 + <dependency>
  111 + <groupId>org.apache.commons</groupId>
  112 + <artifactId>commons-lang3</artifactId>
  113 + <version>3.1</version>
  114 + </dependency>
73 115 </dependencies>
74 116  
75 117 <build>
... ...
springboot/src/main/java/com/sincre/springboot/ApiModel/DeviceToken.java 0 → 100644
... ... @@ -0,0 +1,57 @@
  1 +package com.sincre.springboot.ApiModel;
  2 +
  3 +import com.fasterxml.jackson.annotation.JsonInclude;
  4 +
  5 +@JsonInclude(JsonInclude.Include.NON_EMPTY)
  6 +public class DeviceToken {
  7 +
  8 + private String uid; //用户唯一标识 是
  9 +
  10 + private String timeZoneId; //用户所在时区id,州/省份(Asia/Shanghai) 是
  11 +
  12 + public String getUid() {
  13 + return uid;
  14 + }
  15 +
  16 + public void setUid(String uid) {
  17 + this.uid = uid;
  18 + }
  19 +
  20 + public String getTimeZoneId() {
  21 + return timeZoneId;
  22 + }
  23 +
  24 + public void setTimeZoneId(String timeZoneId) {
  25 + this.timeZoneId = timeZoneId;
  26 + }
  27 +
  28 + public String getLon() {
  29 + return lon;
  30 + }
  31 +
  32 + public void setLon(String lon) {
  33 + this.lon = lon;
  34 + }
  35 +
  36 + public String getLat() {
  37 + return lat;
  38 + }
  39 +
  40 + public void setLat(String lat) {
  41 + this.lat = lat;
  42 + }
  43 +
  44 + public String getLang() {
  45 + return lang;
  46 + }
  47 +
  48 + public void setLang(String lang) {
  49 + this.lang = lang;
  50 + }
  51 +
  52 + private String lon; //经度 否
  53 +
  54 + private String lat; //纬度 否
  55 +
  56 + private String lang; //系统语言,zh,eu等,默认zh 否
  57 +}
... ...
springboot/src/main/java/com/sincre/springboot/ApiModel/TuYaDevicesList.java 0 → 100644
... ... @@ -0,0 +1,14 @@
  1 +package com.sincre.springboot.ApiModel;
  2 +
  3 +import java.awt.*;
  4 +
  5 +public class TuYaDevicesList {
  6 + /**
  7 + * 总数
  8 + */
  9 + public Long total;
  10 + /**
  11 + * 设备列表
  12 + */
  13 + public List devices;
  14 +}
... ...
springboot/src/main/java/com/sincre/springboot/ApiModel/TuYaResResult.java 0 → 100644
... ... @@ -0,0 +1,53 @@
  1 +package com.sincre.springboot.ApiModel;
  2 +
  3 +import com.fasterxml.jackson.annotation.JsonInclude;
  4 +
  5 +@JsonInclude(JsonInclude.Include.NON_EMPTY)
  6 +public class TuYaResResult<T> {
  7 +
  8 + public String getSuccess() {
  9 + return success;
  10 + }
  11 +
  12 + public void setSuccess(String success) {
  13 + this.success = success;
  14 + }
  15 +
  16 + public T getResult() {
  17 + return result;
  18 + }
  19 +
  20 + public void setResult(T result) {
  21 + this.result = result;
  22 + }
  23 +
  24 + public String getCode() {
  25 + return code;
  26 + }
  27 +
  28 + public void setCode(String code) {
  29 + this.code = code;
  30 + }
  31 +
  32 + public String getMsg() {
  33 + return msg;
  34 + }
  35 +
  36 + public void setMsg(String msg) {
  37 + this.msg = msg;
  38 + }
  39 +
  40 + public Long getT() {
  41 + return t;
  42 + }
  43 +
  44 + public void setT(Long t) {
  45 + this.t = t;
  46 + }
  47 +
  48 + private String success;
  49 + private String code;
  50 + private String msg;
  51 + private Long t;
  52 + private T result;
  53 +}
... ...
springboot/src/main/java/com/sincre/springboot/ApiModel/TuYaResTokenObj.java 0 → 100644
... ... @@ -0,0 +1,43 @@
  1 +package com.sincre.springboot.ApiModel;
  2 +
  3 +public class TuYaResTokenObj {
  4 +
  5 + private String uid;
  6 +
  7 + public String getUid() {
  8 + return uid;
  9 + }
  10 +
  11 + public void setUid(String uid) {
  12 + this.uid = uid;
  13 + }
  14 +
  15 + public String getAccess_token() {
  16 + return access_token;
  17 + }
  18 +
  19 + public void setAccess_token(String access_token) {
  20 + this.access_token = access_token;
  21 + }
  22 +
  23 + public int getExpire_time() {
  24 + return expire_time;
  25 + }
  26 +
  27 + public void setExpire_time(int expire_time) {
  28 + this.expire_time = expire_time;
  29 + }
  30 +
  31 + public String getRefresh_token() {
  32 + return refresh_token;
  33 + }
  34 +
  35 + public void setRefresh_token(String refresh_token) {
  36 + this.refresh_token = refresh_token;
  37 + }
  38 +
  39 + private String access_token;
  40 +
  41 + private int expire_time;
  42 + private String refresh_token;
  43 +}
... ...
springboot/src/main/java/com/sincre/springboot/ApiModel/UserInfo.java 0 → 100644
... ... @@ -0,0 +1,68 @@
  1 +package com.sincre.springboot.ApiModel;
  2 +
  3 +import com.fasterxml.jackson.annotation.JsonInclude;
  4 +
  5 +@JsonInclude(JsonInclude.Include.NON_EMPTY)
  6 +public class UserInfo {
  7 +
  8 + /**
  9 + * 国家码 必填项
  10 + * */
  11 + private String country_code;
  12 + /**
  13 + * 用户名,业务方md5加密 是
  14 + */
  15 + private String username;
  16 + /**
  17 + * 用户密码,业务方md5加密 是
  18 + * */
  19 + private String password;
  20 + /**
  21 + * 昵称 否
  22 + */
  23 + private String nick_name;
  24 + /**
  25 + * 用户名类型,1:mobile,2:email,3:username,默认:3 否
  26 + */
  27 + private String username_type;
  28 +
  29 + public String getCountry_code() {
  30 + return country_code;
  31 + }
  32 +
  33 + public void setCountry_code(String country_code) {
  34 + this.country_code = country_code;
  35 + }
  36 +
  37 + public String getUsername() {
  38 + return username;
  39 + }
  40 +
  41 + public void setUsername(String username) {
  42 + this.username = username;
  43 + }
  44 +
  45 + public String getPassword() {
  46 + return password;
  47 + }
  48 +
  49 + public void setPassword(String password) {
  50 + this.password = password;
  51 + }
  52 +
  53 + public String getNick_name() {
  54 + return nick_name;
  55 + }
  56 +
  57 + public void setNick_name(String nick_name) {
  58 + this.nick_name = nick_name;
  59 + }
  60 +
  61 + public String getUsername_type() {
  62 + return username_type;
  63 + }
  64 +
  65 + public void setUsername_type(String username_type) {
  66 + this.username_type = username_type;
  67 + }
  68 +}
... ...
springboot/src/main/java/com/sincre/springboot/ApiPlatform/TuYaCloudService.java 0 → 100644
... ... @@ -0,0 +1,23 @@
  1 +package com.sincre.springboot.ApiPlatform;
  2 +
  3 +import com.sincre.springboot.common.Encript;
  4 +
  5 +public class TuYaCloudService {
  6 + public static String TuYaOpenUrl = "https://openapi.TuYacn.com";
  7 + //公司的账号
  8 + public static String ClientId = "thddfrm97kydyq9wrc8u";
  9 + public static String Secret = "tqcuypeytayths9pudcn937wfupugc3t";
  10 + public static String Sign_method = "HMAC-SHA256";
  11 +
  12 + /**
  13 + * 获取平台访问的签名
  14 + * @param message 消息
  15 + * @param secret 秘钥
  16 + * @return
  17 + */
  18 + public static String createSign(String message, String secret){
  19 +
  20 + return Encript.sha256_HMAC(message,secret).toUpperCase();
  21 + }
  22 +}
  23 +
... ...
springboot/src/main/java/com/sincre/springboot/common/EhcacheUtil.java 0 → 100644
... ... @@ -0,0 +1,230 @@
  1 +package com.sincre.springboot.common;
  2 +
  3 +import com.alibaba.fastjson.JSON;
  4 +import net.sf.ehcache.CacheException;
  5 +import net.sf.ehcache.CacheManager;
  6 +import net.sf.ehcache.Ehcache;
  7 +import net.sf.ehcache.Element;
  8 +
  9 +import java.io.IOException;
  10 +import java.io.InputStream;
  11 +
  12 +public class EhcacheUtil {
  13 +
  14 + /**
  15 + * CacheManage是Ehcache框架的核心接口和类,负责管理一个或多个Cache对象
  16 + */
  17 + private static final CacheManager CACHE_MANAGER = createCacheManager();
  18 +
  19 + /**
  20 + * 描 述: 根据ehcache.xml,创建CacheManager生产器
  21 + * 参 数:
  22 + * 返回值: net.sf.ehcache.CacheManager
  23 + * 创建时间: 2018/5/23
  24 + */
  25 + private static CacheManager createCacheManager() {
  26 + CacheManager cacheManager;
  27 + InputStream input = EhcacheUtil.class.getResourceAsStream("/ehcache.xml");
  28 +
  29 + if (input != null) {
  30 + try {
  31 + cacheManager = CacheManager.create(input);
  32 + } catch (Throwable t) {
  33 + cacheManager = CacheManager.create();
  34 + } finally {
  35 + try {
  36 + input.close();
  37 + } catch (IOException e) {
  38 + }
  39 + }
  40 + } else {
  41 + cacheManager = CacheManager.create();
  42 + }
  43 +
  44 + return cacheManager;
  45 + }
  46 +
  47 + /**
  48 + * The cache id. 缓存所在的位置标识
  49 + */
  50 + private final String id;
  51 +
  52 + /**
  53 + * 创建EhCache
  54 + */
  55 + public EhcacheUtil(){
  56 + this.id = this.getClass().getName();
  57 + if (!CACHE_MANAGER.cacheExists(this.id)) {
  58 + CACHE_MANAGER.addCache(this.id);
  59 + }
  60 + }
  61 +
  62 + /**
  63 + * 得到当前缓存
  64 + * @return
  65 + */
  66 + private Ehcache getCache() {
  67 + return CACHE_MANAGER.getCache(this.id);
  68 + }
  69 +
  70 + /**
  71 + * 写入EhCache,当前实例对象T,同时转成Json格式
  72 + * @param key
  73 + * @param value
  74 + * @param <T>
  75 + */
  76 + public <T> void set(String key, T value){
  77 + setObject(key, JSON.toJSONString(value));
  78 + }
  79 +
  80 + /**
  81 + * 写入EhCache,字符串对象
  82 + * @param key
  83 + * @param value
  84 + */
  85 + public void set(String key, String value){
  86 + setObject(key,value);
  87 + }
  88 +
  89 + /**
  90 + * 写入EhCache,当前实例对象T, 同时转成Json格式,并设置失效时间
  91 + * @param key
  92 + * @param value
  93 + * @param time
  94 + * @param <T>
  95 + */
  96 + public <T> void setex(String key, T value, int time){
  97 + setexObject(key, JSON.toJSONString(value),time);
  98 + }
  99 +
  100 + /**
  101 + * 写入EhCache,字符串对象,并设置失效时间
  102 + * @param key
  103 + * @param value
  104 + * @param time
  105 + */
  106 + public void setex(String key, String value, int time){
  107 + setexObject(key,value,time);
  108 + }
  109 +
  110 + /**
  111 + * 存入EhCache缓存
  112 + * @param key
  113 + * @param value
  114 + */
  115 + public void setObject(String key, Object value) {
  116 + try {
  117 + this.getCache().put(new Element(key, value));
  118 + } catch (Throwable t) {
  119 + throw new CacheException(t.getMessage(),t);
  120 + }
  121 + }
  122 +
  123 + /**
  124 + * 存入EhCache缓存,并设置失效时间
  125 + * @param key
  126 + * @param value
  127 + * @param time
  128 + */
  129 + public void setexObject(String key, Object value, int time) {
  130 + Element element = new Element(key, value);
  131 + element.setTimeToLive(time);
  132 + try {
  133 + this.getCache().put(element);
  134 + } catch (Throwable t) {
  135 + throw new CacheException(t.getMessage(),t);
  136 + }
  137 + }
  138 +
  139 + /**
  140 + * 获取EhCache对象,字符串对象
  141 + * @param key
  142 + * @return
  143 + */
  144 + public String get(String key){
  145 + Object value = getObject(key);
  146 + return value == null ? "" : value.toString();
  147 + }
  148 +
  149 + /**
  150 + * 获取EhCache对象,当前实例对象T
  151 + * @param key
  152 + * @param clazz
  153 + * @param <T>
  154 + * @return
  155 + */
  156 + public <T> T get(String key, Class<T> clazz){
  157 + Object obj = getObject(key);
  158 + if(obj == null){
  159 + return null;
  160 + }
  161 + return JSON.parseObject(getObject(key).toString(),clazz);
  162 + }
  163 +
  164 + /**
  165 + * 根据Key获取缓存对象
  166 + * @param key
  167 + * @return
  168 + */
  169 + public Object getObject(String key) {
  170 + try {
  171 + Element cachedElement = this.getCache().get(key);
  172 + if (cachedElement == null) {
  173 + return null;
  174 + }
  175 + return cachedElement.getObjectValue();
  176 + } catch (Exception t) {
  177 + throw new CacheException(t.getMessage(),t);
  178 + }
  179 + }
  180 +
  181 + /**
  182 + * 删除当前Cache的key
  183 + * @param key
  184 + */
  185 + public void remove(String key) {
  186 + try {
  187 + this.getCache().remove(key);
  188 + } catch (Throwable t) {
  189 + throw new CacheException(t.getMessage(),t);
  190 + }
  191 + }
  192 +
  193 + /**
  194 + * 获取当前Cache的数目
  195 + * @return
  196 + */
  197 + public Long dbSize() {
  198 + try {
  199 + return Long.valueOf(this.getCache().getSize());
  200 + } catch (Throwable t) {
  201 + throw new CacheException(t.getMessage(),t);
  202 + }
  203 + }
  204 +
  205 + /**
  206 + * 清空当前Cache的所有缓存
  207 + */
  208 + public void flushDB() {
  209 + this.getCache().removeAll();
  210 + }
  211 +
  212 +
  213 + /**
  214 + * 重写hashCode
  215 + * @return
  216 + */
  217 + @Override
  218 + public int hashCode() {
  219 + return this.id.hashCode();
  220 + }
  221 +
  222 + /**
  223 + * 重写toString
  224 + * @return
  225 + */
  226 + @Override
  227 + public String toString() {
  228 + return "EHCache {" + this.id + "}";
  229 + }
  230 +}
... ...
springboot/src/main/java/com/sincre/springboot/common/Encript.java 0 → 100644
... ... @@ -0,0 +1,46 @@
  1 +package com.sincre.springboot.common;
  2 +
  3 +import javax.crypto.Mac;
  4 +import javax.crypto.spec.SecretKeySpec;
  5 +
  6 +public class Encript {
  7 +
  8 + /**
  9 + * 将加密后的字节数组转换成字符串(原始64位)
  10 + *
  11 + * @param b 字节数组
  12 + * @return 字符串
  13 + */
  14 + public static String byteArrayToHexString(byte[] b) {
  15 + StringBuilder hs = new StringBuilder();
  16 + String stmp;
  17 + for (int n = 0; b!=null && n < b.length; n++) {
  18 + stmp = Integer.toHexString(b[n] & 0XFF);
  19 + if (stmp.length() == 1)
  20 + hs.append('0');
  21 + hs.append(stmp);
  22 + }
  23 + return hs.toString().toLowerCase();
  24 + }
  25 +
  26 + /**
  27 + * sha256_HMAC加密
  28 + * @param message 消息
  29 + * @param secret 秘钥
  30 + * @return 加密后字符串
  31 + * */
  32 + public static String sha256_HMAC(String message, String secret) {
  33 + String hash = "";
  34 + try {
  35 + Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
  36 + SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
  37 + sha256_HMAC.init(secret_key);
  38 + byte[] bytes = sha256_HMAC.doFinal(message.getBytes());
  39 + hash = byteArrayToHexString(bytes);
  40 + System.out.println(hash);
  41 + } catch (Exception e) {
  42 + System.out.println("Error HmacSHA256 ===========" + e.getMessage());
  43 + }
  44 + return hash;
  45 + }
  46 +}
... ...
springboot/src/main/java/com/sincre/springboot/controller/TuYaYunController.java 0 → 100644
... ... @@ -0,0 +1,188 @@
  1 +package com.sincre.springboot.controller;
  2 +
  3 +import com.fasterxml.jackson.core.type.TypeReference;
  4 +import com.fasterxml.jackson.databind.ObjectMapper;
  5 +import com.sincre.springboot.ApiModel.*;
  6 +import com.sincre.springboot.ApiPlatform.TuYaCloudService;
  7 +import com.sincre.springboot.common.EhcacheUtil;
  8 +import com.sincre.springboot.utils.ApiHelper;
  9 +import io.swagger.annotations.Api;
  10 +import org.apache.commons.lang3.StringUtils;
  11 +import org.springframework.web.bind.annotation.*;
  12 +
  13 +import java.util.HashMap;
  14 +import java.util.Map;
  15 +
  16 +@RestController
  17 +@RequestMapping(value = "/TuYa/*")
  18 +@Api(value = "涂鸦云服务API调用")
  19 +public class TuYaYunController {
  20 +
  21 + @GetMapping("GetToken")
  22 + public TuYaResResult getTuYaToken(){
  23 +
  24 + String apiUrl = "/v1.0/token?grant_type=1";
  25 + Long t = System.currentTimeMillis();
  26 + //Token获取前的签名
  27 + String sign = TuYaCloudService.createSign(TuYaCloudService.ClientId+t,TuYaCloudService.Secret);
  28 + Map<String,String> map = new HashMap();
  29 + map.put("client_id", TuYaCloudService.ClientId);
  30 + map.put("sign",sign);
  31 + map.put("sign_method",TuYaCloudService.Sign_method);
  32 + map.put("t",t.toString());
  33 + String result = ApiHelper.doGet(TuYaCloudService.TuYaOpenUrl + apiUrl,map);
  34 +
  35 + TuYaResResult<TuYaResTokenObj> resResult = new TuYaResResult<>();
  36 + try{
  37 + ObjectMapper objectMapper = new ObjectMapper();
  38 + resResult = objectMapper.readValue(result,new TypeReference<TuYaResResult<TuYaResTokenObj>>(){});
  39 +
  40 + String access_Token = resResult.getResult().getAccess_token(); //存储第一次获取的Token
  41 + EhcacheUtil ehcacheUtil = new EhcacheUtil();
  42 + ehcacheUtil.setex("TuYa_Token",access_Token,60);
  43 + } catch(Exception ex){
  44 + System.out.println(ex.getMessage());
  45 + }
  46 +
  47 + return resResult;
  48 + }
  49 +
  50 + @GetMapping("GetDevicesInfo")
  51 + public TuYaResResult getTuYaDevicesInfo(){
  52 +
  53 + EhcacheUtil ehcacheUtil = new EhcacheUtil();
  54 + String apiUrl = "/v1.0/devices?device_ids=";
  55 + Long t = System.currentTimeMillis();
  56 + String access_Token = ehcacheUtil.get("TuYa_Token");
  57 + String sign = TuYaCloudService.createSign(TuYaCloudService.ClientId+access_Token+t,TuYaCloudService.Secret);
  58 + Map<String,String> map = new HashMap();
  59 + map.put("client_id", TuYaCloudService.ClientId);
  60 + map.put("access_token",access_Token);
  61 + map.put("sign",sign);
  62 + map.put("sign_method",TuYaCloudService.Sign_method);
  63 + map.put("t",t.toString());
  64 + String result = ApiHelper.doGet(TuYaCloudService.TuYaOpenUrl + apiUrl,map);
  65 +
  66 + TuYaResResult<TuYaDevicesList> resResult = null;
  67 + try{
  68 + ObjectMapper objectMapper = new ObjectMapper();
  69 + TypeReference<TuYaResResult<TuYaDevicesList>> reference = new TypeReference<TuYaResResult<TuYaDevicesList>>(){};
  70 + resResult = objectMapper.readValue(result,reference);
  71 + System.out.println(resResult.getResult().total);
  72 + } catch(Exception ex){
  73 + System.out.println(ex.getMessage());
  74 + }
  75 +
  76 + System.out.println(result);
  77 + return resResult;
  78 + }
  79 +
  80 +
  81 + /**
  82 + * 根据schema分页获取开发者App下的用户列表
  83 + * @param AppId 应用标识
  84 + * @param pageIndex 页码
  85 + * @param pageSize 大小
  86 + * @return
  87 + */
  88 + @GetMapping("{AppId}/GetTuYaAPPUser")
  89 + public String getTuYaAPPUser(@PathVariable("AppId") String AppId, @RequestParam int pageIndex, @RequestParam int pageSize){
  90 +
  91 + EhcacheUtil ehcacheUtil = new EhcacheUtil();
  92 +
  93 + String apiUrl = String.format("/v1.0/apps/%s/users?page_no=%d&page_size=%d",AppId,pageIndex,pageSize);//iotshunzhi
  94 + Long t = System.currentTimeMillis();
  95 + String access_Token = ehcacheUtil.get("TuYa_Token");
  96 + System.out.println(access_Token);
  97 + //Token获取后的签名
  98 + String sign = TuYaCloudService.createSign(TuYaCloudService.ClientId+access_Token+t,TuYaCloudService.Secret);
  99 + Map<String,String> headMap = new HashMap();
  100 + headMap.put("client_id", TuYaCloudService.ClientId);
  101 + headMap.put("access_token",access_Token);
  102 + headMap.put("sign",sign);
  103 + headMap.put("sign_method",TuYaCloudService.Sign_method);
  104 + headMap.put("t",t.toString());
  105 +
  106 + String result = ApiHelper.doGet(TuYaCloudService.TuYaOpenUrl + apiUrl,headMap);
  107 +
  108 + return result;
  109 + }
  110 +
  111 +
  112 + @PostMapping("{AppId}/AddTuYaAPPUser")
  113 + public String addTuYaAPPUser(@PathVariable("AppId") String AppId,@RequestBody UserInfo userInfo){
  114 +
  115 + EhcacheUtil ehcacheUtil = new EhcacheUtil();
  116 +
  117 + String apiUrl = String.format("/v1.0/apps/%s/user",AppId);//应用标识iotshunzhi
  118 + Long t = System.currentTimeMillis();
  119 + String access_Token = ehcacheUtil.get("TuYa_Token");
  120 + //Token获取后的签名
  121 + String sign = TuYaCloudService.createSign(TuYaCloudService.ClientId+access_Token+t,TuYaCloudService.Secret);
  122 + Map<String,String> headMap = new HashMap();
  123 + headMap.put("client_id", TuYaCloudService.ClientId);
  124 + headMap.put("access_token",access_Token);
  125 + headMap.put("sign",sign);
  126 + headMap.put("sign_method",TuYaCloudService.Sign_method);
  127 + headMap.put("t",t.toString());
  128 +
  129 + ObjectMapper objectMapper = new ObjectMapper();
  130 +
  131 + String jsonResult = "";
  132 + try {
  133 + jsonResult = objectMapper.writeValueAsString(userInfo);
  134 + System.out.println(jsonResult);
  135 + }catch (com.fasterxml.jackson.core.JsonProcessingException ex){
  136 + ex.printStackTrace();
  137 + }
  138 +
  139 + String result = ApiHelper.doPost(TuYaCloudService.TuYaOpenUrl + apiUrl,headMap,jsonResult);
  140 +
  141 + TuYaResResult<UserInfo> resResult = null;
  142 +
  143 + return result;
  144 + }
  145 +
  146 + /**
  147 + * 生成配网的Token
  148 + * @return
  149 + */
  150 + @GetMapping("AddDevicesToken")
  151 + public String addDevicesToken(@RequestParam String UId){
  152 +
  153 + EhcacheUtil ehcacheUtil = new EhcacheUtil();
  154 +
  155 + String apiUrl = String.format("/v1.0/devices/token");
  156 + Long t = System.currentTimeMillis();
  157 + String access_Token = ehcacheUtil.get("TuYa_Token");
  158 + //Token获取后的签名
  159 + String sign = TuYaCloudService.createSign(TuYaCloudService.ClientId+access_Token+t,TuYaCloudService.Secret);
  160 + System.out.println("签名"+sign);
  161 + Map<String,String> map = new HashMap();
  162 + map.put("client_id", TuYaCloudService.ClientId);
  163 + map.put("access_token",access_Token);
  164 + map.put("sign",sign);
  165 + map.put("sign_method",TuYaCloudService.Sign_method);
  166 + map.put("t",t.toString());
  167 +
  168 + if(StringUtils.isNotBlank(UId)){
  169 + UId = "ay1557735327941UvZAG";
  170 + }
  171 +
  172 + ObjectMapper objectMapper = new ObjectMapper();
  173 + DeviceToken deviceToken = new DeviceToken();
  174 + deviceToken.setUid(UId);
  175 + deviceToken.setTimeZoneId("Asia/ZheJiang");
  176 +
  177 + String jsonResult = "";
  178 + try {
  179 + jsonResult = objectMapper.writeValueAsString(deviceToken);
  180 + System.out.println(jsonResult);
  181 + }catch (com.fasterxml.jackson.core.JsonProcessingException ex){
  182 + ex.printStackTrace();
  183 + }
  184 + String result = ApiHelper.doPost(TuYaCloudService.TuYaOpenUrl + apiUrl,map,jsonResult);
  185 +
  186 + return result;
  187 + }
  188 +}
... ...
springboot/src/main/java/com/sincre/springboot/utils/ApiHelper.java 0 → 100644
... ... @@ -0,0 +1,200 @@
  1 +package com.sincre.springboot.utils;
  2 +
  3 +import org.apache.http.HttpEntity;
  4 +import org.apache.http.NameValuePair;
  5 +import org.apache.http.client.ClientProtocolException;
  6 +import org.apache.http.client.config.RequestConfig;
  7 +import org.apache.http.client.entity.UrlEncodedFormEntity;
  8 +import org.apache.http.client.methods.CloseableHttpResponse;
  9 +import org.apache.http.client.methods.HttpGet;
  10 +import org.apache.http.client.methods.HttpPost;
  11 +import org.apache.http.entity.ContentType;
  12 +import org.apache.http.entity.StringEntity;
  13 +import org.apache.http.impl.client.CloseableHttpClient;
  14 +import org.apache.http.impl.client.HttpClients;
  15 +import org.apache.http.message.BasicNameValuePair;
  16 +import org.apache.http.util.EntityUtils;
  17 +
  18 +import java.io.IOException;
  19 +import java.io.UnsupportedEncodingException;
  20 +import java.util.*;
  21 +
  22 +public class ApiHelper {
  23 +
  24 + public static String doGet(String url,Map<String, String> headerParamMap) {
  25 + CloseableHttpClient httpClient = null;
  26 + CloseableHttpResponse response = null;
  27 + String result = "";
  28 + try {
  29 + // 通过址默认配置创建一个httpClient实例
  30 + httpClient = HttpClients.createDefault();
  31 + // 创建httpGet远程连接实例
  32 + HttpGet httpGet = new HttpGet(url);
  33 + // 设置请求头信息,
  34 + for (Map.Entry<String, String> entry : headerParamMap.entrySet()) {
  35 + httpGet.setHeader(entry.getKey(),entry.getValue());
  36 + }
  37 +
  38 + // 设置配置请求参数
  39 + RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 连接主机服务超时时间
  40 + .setConnectionRequestTimeout(35000)// 请求超时时间
  41 + .setSocketTimeout(60000)// 数据读取超时时间
  42 + .build();
  43 + // 为httpGet实例设置配置
  44 + httpGet.setConfig(requestConfig);
  45 + // 执行get请求得到返回对象
  46 + response = httpClient.execute(httpGet);
  47 + // 通过返回对象获取返回数据
  48 + HttpEntity entity = response.getEntity();
  49 + // 通过EntityUtils中的toString方法将结果转换为字符串
  50 + result = EntityUtils.toString(entity);
  51 + } catch (ClientProtocolException e) {
  52 + e.printStackTrace();
  53 + } catch (IOException e) {
  54 + e.printStackTrace();
  55 + } finally {
  56 + // 关闭资源
  57 + if (null != response) {
  58 + try {
  59 + response.close();
  60 + } catch (IOException e) {
  61 + e.printStackTrace();
  62 + }
  63 + }
  64 + if (null != httpClient) {
  65 + try {
  66 + httpClient.close();
  67 + } catch (IOException e) {
  68 + e.printStackTrace();
  69 + }
  70 + }
  71 + }
  72 + return result;
  73 + }
  74 +
  75 + /**
  76 + * 表单格式的post请求
  77 + * @param url 接口地址
  78 + * @param headerParamMap 设置请求头
  79 + * @param paramMap 设置请求值
  80 + * @return
  81 + */
  82 + public static String doPost(String url,Map<String, String> headerParamMap, Map<String, Object> paramMap) {
  83 + CloseableHttpClient httpClient ;
  84 + String result;
  85 + // 创建httpClient实例
  86 + httpClient = HttpClients.createDefault();
  87 + // 创建httpPost远程连接实例
  88 + HttpPost httpPost = new HttpPost(url);
  89 + // 设置请求头
  90 + httpPost.addHeader("Content-Type", "application/json");
  91 + for (Map.Entry<String, String> entry : headerParamMap.entrySet()) {
  92 + httpPost.setHeader(entry.getKey(),entry.getValue());
  93 + }
  94 + // 配置请求参数实例
  95 + RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 设置连接主机服务超时时间
  96 + .setConnectionRequestTimeout(35000)// 设置连接请求超时时间
  97 + .setSocketTimeout(60000)// 设置读取数据连接超时时间
  98 + .build();
  99 + // 为httpPost实例设置配置
  100 + httpPost.setConfig(requestConfig);
  101 +
  102 + // 封装post请求参数
  103 + if (null != paramMap && paramMap.size() > 0) {
  104 + List<NameValuePair> nvps = new ArrayList<NameValuePair>();
  105 + // 通过map集成entrySet方法获取entity
  106 + Set<Map.Entry<String, Object>> entrySet = paramMap.entrySet();
  107 + // 循环遍历,获取迭代器
  108 + Iterator<Map.Entry<String, Object>> iterator = entrySet.iterator();
  109 + while (iterator.hasNext()) {
  110 + Map.Entry<String, Object> mapEntry = iterator.next();
  111 + nvps.add(new BasicNameValuePair(mapEntry.getKey(), mapEntry.getValue().toString()));
  112 + }
  113 +
  114 + // 为httpPost设置封装好的请求参数
  115 + try {
  116 + UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nvps, "UTF-8");
  117 + entity.setContentType("application/json");
  118 + httpPost.setEntity(entity);
  119 + } catch (UnsupportedEncodingException e) {
  120 + e.printStackTrace();
  121 + }
  122 + }
  123 + result = closeHttpAndResult(httpClient,httpPost);
  124 + return result;
  125 + }
  126 +
  127 + /**
  128 + * post请求,内容体比较灵活,任意字符串格式的内容
  129 + * @param url
  130 + * @param headerParamMap
  131 + * @param jsonParam
  132 + * @return
  133 + */
  134 + public static String doPost(String url, Map<String, String> headerParamMap, String jsonParam) {
  135 + CloseableHttpClient httpClient;
  136 +// CloseableHttpResponse httpResponse = null;
  137 + String result;
  138 + // 创建httpClient实例
  139 + httpClient = HttpClients.createDefault();
  140 + // 创建httpPost远程连接实例
  141 + HttpPost httpPost = new HttpPost(url);
  142 + // 设置请求头
  143 + httpPost.addHeader("Content-Type", "application/json");
  144 + for (Map.Entry<String, String> entry : headerParamMap.entrySet()) {
  145 + httpPost.setHeader(entry.getKey(),entry.getValue());
  146 + }
  147 + // 配置请求参数实例
  148 + RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 设置连接主机服务超时时间
  149 + .setConnectionRequestTimeout(35000)// 设置连接请求超时时间
  150 + .setSocketTimeout(60000)// 设置读取数据连接超时时间
  151 + .build();
  152 + // 为httpPost实例设置配置
  153 + httpPost.setConfig(requestConfig);
  154 +// try {
  155 + StringEntity stringEntity = new StringEntity(jsonParam, ContentType.create("application/json","UTF-8"));
  156 +// stringEntity.setContentType("application/json");
  157 +// stringEntity.setContentEncoding("gzip");//请求头的编码格式
  158 + httpPost.setEntity(stringEntity);
  159 +// }catch (UnsupportedEncodingException e){
  160 +// e.printStackTrace();
  161 +// }
  162 + result = closeHttpAndResult(httpClient,httpPost);
  163 + return result;
  164 + }
  165 +
  166 + private static String closeHttpAndResult(CloseableHttpClient httpClient,HttpPost httpPost){
  167 + CloseableHttpResponse httpResponse = null;
  168 + String result = null;
  169 + try {
  170 + // httpClient对象执行post请求,并返回响应参数对象
  171 + httpResponse = httpClient.execute(httpPost);
  172 + // 从响应对象中获取响应内容
  173 + HttpEntity entity = httpResponse.getEntity();
  174 + result = EntityUtils.toString(entity);
  175 + } catch (ClientProtocolException e) {
  176 + e.printStackTrace();
  177 + } catch (IOException e) {
  178 + e.printStackTrace();
  179 + } finally {
  180 + // 关闭资源
  181 + if (null != httpResponse) {
  182 + try {
  183 + httpResponse.close();
  184 + } catch (IOException e) {
  185 + e.printStackTrace();
  186 + }
  187 + }
  188 + if (null != httpClient) {
  189 + try {
  190 + httpClient.close();
  191 + } catch (IOException e) {
  192 + e.printStackTrace();
  193 + }
  194 + }
  195 + }
  196 +
  197 + return result;
  198 + }
  199 +}
  200 +
... ...