diff --git a/springboot/pom.xml b/springboot/pom.xml index 92cf2b2..69383fc 100644 --- a/springboot/pom.xml +++ b/springboot/pom.xml @@ -23,12 +23,12 @@ org.springframework.boot spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-tomcat - - + + + + + + @@ -38,6 +38,12 @@ org.springframework.boot + spring-boot-starter-tomcat + provided + + + + org.springframework.boot spring-boot-starter-test test @@ -70,6 +76,42 @@ mybatis-spring-boot-starter 2.0.0 + + + + org.apache.httpcomponents + httpclient + 4.5.3 + + + + + com.fasterxml.jackson.core + jackson-databind + 2.9.8 + + + + com.alibaba + fastjson + 1.2.58 + + + + org.springframework.boot + spring-boot-starter-cache + + + + net.sf.ehcache + ehcache + + + + org.apache.commons + commons-lang3 + 3.1 + diff --git a/springboot/src/main/java/com/sincre/springboot/ApiModel/DeviceToken.java b/springboot/src/main/java/com/sincre/springboot/ApiModel/DeviceToken.java new file mode 100644 index 0000000..53b3094 --- /dev/null +++ b/springboot/src/main/java/com/sincre/springboot/ApiModel/DeviceToken.java @@ -0,0 +1,57 @@ +package com.sincre.springboot.ApiModel; + +import com.fasterxml.jackson.annotation.JsonInclude; + +@JsonInclude(JsonInclude.Include.NON_EMPTY) +public class DeviceToken { + + private String uid; //用户唯一标识 是 + + private String timeZoneId; //用户所在时区id,州/省份(Asia/Shanghai) 是 + + public String getUid() { + return uid; + } + + public void setUid(String uid) { + this.uid = uid; + } + + public String getTimeZoneId() { + return timeZoneId; + } + + public void setTimeZoneId(String timeZoneId) { + this.timeZoneId = timeZoneId; + } + + public String getLon() { + return lon; + } + + public void setLon(String lon) { + this.lon = lon; + } + + public String getLat() { + return lat; + } + + public void setLat(String lat) { + this.lat = lat; + } + + public String getLang() { + return lang; + } + + public void setLang(String lang) { + this.lang = lang; + } + + private String lon; //经度 否 + + private String lat; //纬度 否 + + private String lang; //系统语言,zh,eu等,默认zh 否 +} diff --git a/springboot/src/main/java/com/sincre/springboot/ApiModel/TuYaDevicesList.java b/springboot/src/main/java/com/sincre/springboot/ApiModel/TuYaDevicesList.java new file mode 100644 index 0000000..1e90735 --- /dev/null +++ b/springboot/src/main/java/com/sincre/springboot/ApiModel/TuYaDevicesList.java @@ -0,0 +1,14 @@ +package com.sincre.springboot.ApiModel; + +import java.awt.*; + +public class TuYaDevicesList { + /** + * 总数 + */ + public Long total; + /** + * 设备列表 + */ + public List devices; +} diff --git a/springboot/src/main/java/com/sincre/springboot/ApiModel/TuYaResResult.java b/springboot/src/main/java/com/sincre/springboot/ApiModel/TuYaResResult.java new file mode 100644 index 0000000..2161a55 --- /dev/null +++ b/springboot/src/main/java/com/sincre/springboot/ApiModel/TuYaResResult.java @@ -0,0 +1,53 @@ +package com.sincre.springboot.ApiModel; + +import com.fasterxml.jackson.annotation.JsonInclude; + +@JsonInclude(JsonInclude.Include.NON_EMPTY) +public class TuYaResResult { + + public String getSuccess() { + return success; + } + + public void setSuccess(String success) { + this.success = success; + } + + public T getResult() { + return result; + } + + public void setResult(T result) { + this.result = result; + } + + public String getCode() { + return code; + } + + public void setCode(String code) { + this.code = code; + } + + public String getMsg() { + return msg; + } + + public void setMsg(String msg) { + this.msg = msg; + } + + public Long getT() { + return t; + } + + public void setT(Long t) { + this.t = t; + } + + private String success; + private String code; + private String msg; + private Long t; + private T result; +} diff --git a/springboot/src/main/java/com/sincre/springboot/ApiModel/TuYaResTokenObj.java b/springboot/src/main/java/com/sincre/springboot/ApiModel/TuYaResTokenObj.java new file mode 100644 index 0000000..a0eea1c --- /dev/null +++ b/springboot/src/main/java/com/sincre/springboot/ApiModel/TuYaResTokenObj.java @@ -0,0 +1,43 @@ +package com.sincre.springboot.ApiModel; + +public class TuYaResTokenObj { + + private String uid; + + public String getUid() { + return uid; + } + + public void setUid(String uid) { + this.uid = uid; + } + + public String getAccess_token() { + return access_token; + } + + public void setAccess_token(String access_token) { + this.access_token = access_token; + } + + public int getExpire_time() { + return expire_time; + } + + public void setExpire_time(int expire_time) { + this.expire_time = expire_time; + } + + public String getRefresh_token() { + return refresh_token; + } + + public void setRefresh_token(String refresh_token) { + this.refresh_token = refresh_token; + } + + private String access_token; + + private int expire_time; + private String refresh_token; +} diff --git a/springboot/src/main/java/com/sincre/springboot/ApiModel/UserInfo.java b/springboot/src/main/java/com/sincre/springboot/ApiModel/UserInfo.java new file mode 100644 index 0000000..1ee664e --- /dev/null +++ b/springboot/src/main/java/com/sincre/springboot/ApiModel/UserInfo.java @@ -0,0 +1,68 @@ +package com.sincre.springboot.ApiModel; + +import com.fasterxml.jackson.annotation.JsonInclude; + +@JsonInclude(JsonInclude.Include.NON_EMPTY) +public class UserInfo { + + /** + * 国家码 必填项 + * */ + private String country_code; + /** + * 用户名,业务方md5加密 是 + */ + private String username; + /** + * 用户密码,业务方md5加密 是 + * */ + private String password; + /** + * 昵称 否 + */ + private String nick_name; + /** + * 用户名类型,1:mobile,2:email,3:username,默认:3 否 + */ + private String username_type; + + public String getCountry_code() { + return country_code; + } + + public void setCountry_code(String country_code) { + this.country_code = country_code; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getNick_name() { + return nick_name; + } + + public void setNick_name(String nick_name) { + this.nick_name = nick_name; + } + + public String getUsername_type() { + return username_type; + } + + public void setUsername_type(String username_type) { + this.username_type = username_type; + } +} diff --git a/springboot/src/main/java/com/sincre/springboot/ApiPlatform/TuYaCloudService.java b/springboot/src/main/java/com/sincre/springboot/ApiPlatform/TuYaCloudService.java new file mode 100644 index 0000000..a02def1 --- /dev/null +++ b/springboot/src/main/java/com/sincre/springboot/ApiPlatform/TuYaCloudService.java @@ -0,0 +1,23 @@ +package com.sincre.springboot.ApiPlatform; + +import com.sincre.springboot.common.Encript; + +public class TuYaCloudService { + public static String TuYaOpenUrl = "https://openapi.TuYacn.com"; + //公司的账号 + public static String ClientId = "thddfrm97kydyq9wrc8u"; + public static String Secret = "tqcuypeytayths9pudcn937wfupugc3t"; + public static String Sign_method = "HMAC-SHA256"; + + /** + * 获取平台访问的签名 + * @param message 消息 + * @param secret 秘钥 + * @return + */ + public static String createSign(String message, String secret){ + + return Encript.sha256_HMAC(message,secret).toUpperCase(); + } +} + diff --git a/springboot/src/main/java/com/sincre/springboot/common/EhcacheUtil.java b/springboot/src/main/java/com/sincre/springboot/common/EhcacheUtil.java new file mode 100644 index 0000000..9266c8a --- /dev/null +++ b/springboot/src/main/java/com/sincre/springboot/common/EhcacheUtil.java @@ -0,0 +1,230 @@ +package com.sincre.springboot.common; + +import com.alibaba.fastjson.JSON; +import net.sf.ehcache.CacheException; +import net.sf.ehcache.CacheManager; +import net.sf.ehcache.Ehcache; +import net.sf.ehcache.Element; + +import java.io.IOException; +import java.io.InputStream; + +public class EhcacheUtil { + + /** + * CacheManage是Ehcache框架的核心接口和类,负责管理一个或多个Cache对象 + */ + private static final CacheManager CACHE_MANAGER = createCacheManager(); + + /** + * 描 述: 根据ehcache.xml,创建CacheManager生产器 + * 参 数: + * 返回值: net.sf.ehcache.CacheManager + * 创建时间: 2018/5/23 + */ + private static CacheManager createCacheManager() { + CacheManager cacheManager; + InputStream input = EhcacheUtil.class.getResourceAsStream("/ehcache.xml"); + + if (input != null) { + try { + cacheManager = CacheManager.create(input); + } catch (Throwable t) { + cacheManager = CacheManager.create(); + } finally { + try { + input.close(); + } catch (IOException e) { + } + } + } else { + cacheManager = CacheManager.create(); + } + + return cacheManager; + } + + /** + * The cache id. 缓存所在的位置标识 + */ + private final String id; + + /** + * 创建EhCache + */ + public EhcacheUtil(){ + this.id = this.getClass().getName(); + if (!CACHE_MANAGER.cacheExists(this.id)) { + CACHE_MANAGER.addCache(this.id); + } + } + + /** + * 得到当前缓存 + * @return + */ + private Ehcache getCache() { + return CACHE_MANAGER.getCache(this.id); + } + + /** + * 写入EhCache,当前实例对象T,同时转成Json格式 + * @param key + * @param value + * @param + */ + public void set(String key, T value){ + setObject(key, JSON.toJSONString(value)); + } + + /** + * 写入EhCache,字符串对象 + * @param key + * @param value + */ + public void set(String key, String value){ + setObject(key,value); + } + + /** + * 写入EhCache,当前实例对象T, 同时转成Json格式,并设置失效时间 + * @param key + * @param value + * @param time + * @param + */ + public void setex(String key, T value, int time){ + setexObject(key, JSON.toJSONString(value),time); + } + + /** + * 写入EhCache,字符串对象,并设置失效时间 + * @param key + * @param value + * @param time + */ + public void setex(String key, String value, int time){ + setexObject(key,value,time); + } + + /** + * 存入EhCache缓存 + * @param key + * @param value + */ + public void setObject(String key, Object value) { + try { + this.getCache().put(new Element(key, value)); + } catch (Throwable t) { + throw new CacheException(t.getMessage(),t); + } + } + + /** + * 存入EhCache缓存,并设置失效时间 + * @param key + * @param value + * @param time + */ + public void setexObject(String key, Object value, int time) { + Element element = new Element(key, value); + element.setTimeToLive(time); + try { + this.getCache().put(element); + } catch (Throwable t) { + throw new CacheException(t.getMessage(),t); + } + } + + /** + * 获取EhCache对象,字符串对象 + * @param key + * @return + */ + public String get(String key){ + Object value = getObject(key); + return value == null ? "" : value.toString(); + } + + /** + * 获取EhCache对象,当前实例对象T + * @param key + * @param clazz + * @param + * @return + */ + public T get(String key, Class clazz){ + Object obj = getObject(key); + if(obj == null){ + return null; + } + return JSON.parseObject(getObject(key).toString(),clazz); + } + + /** + * 根据Key获取缓存对象 + * @param key + * @return + */ + public Object getObject(String key) { + try { + Element cachedElement = this.getCache().get(key); + if (cachedElement == null) { + return null; + } + return cachedElement.getObjectValue(); + } catch (Exception t) { + throw new CacheException(t.getMessage(),t); + } + } + + /** + * 删除当前Cache的key + * @param key + */ + public void remove(String key) { + try { + this.getCache().remove(key); + } catch (Throwable t) { + throw new CacheException(t.getMessage(),t); + } + } + + /** + * 获取当前Cache的数目 + * @return + */ + public Long dbSize() { + try { + return Long.valueOf(this.getCache().getSize()); + } catch (Throwable t) { + throw new CacheException(t.getMessage(),t); + } + } + + /** + * 清空当前Cache的所有缓存 + */ + public void flushDB() { + this.getCache().removeAll(); + } + + + /** + * 重写hashCode + * @return + */ + @Override + public int hashCode() { + return this.id.hashCode(); + } + + /** + * 重写toString + * @return + */ + @Override + public String toString() { + return "EHCache {" + this.id + "}"; + } +} diff --git a/springboot/src/main/java/com/sincre/springboot/common/Encript.java b/springboot/src/main/java/com/sincre/springboot/common/Encript.java new file mode 100644 index 0000000..480f84e --- /dev/null +++ b/springboot/src/main/java/com/sincre/springboot/common/Encript.java @@ -0,0 +1,46 @@ +package com.sincre.springboot.common; + +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; + +public class Encript { + + /** + * 将加密后的字节数组转换成字符串(原始64位) + * + * @param b 字节数组 + * @return 字符串 + */ + public static String byteArrayToHexString(byte[] b) { + StringBuilder hs = new StringBuilder(); + String stmp; + for (int n = 0; b!=null && n < b.length; n++) { + stmp = Integer.toHexString(b[n] & 0XFF); + if (stmp.length() == 1) + hs.append('0'); + hs.append(stmp); + } + return hs.toString().toLowerCase(); + } + + /** + * sha256_HMAC加密 + * @param message 消息 + * @param secret 秘钥 + * @return 加密后字符串 + * */ + public static String sha256_HMAC(String message, String secret) { + String hash = ""; + try { + Mac sha256_HMAC = Mac.getInstance("HmacSHA256"); + SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256"); + sha256_HMAC.init(secret_key); + byte[] bytes = sha256_HMAC.doFinal(message.getBytes()); + hash = byteArrayToHexString(bytes); + System.out.println(hash); + } catch (Exception e) { + System.out.println("Error HmacSHA256 ===========" + e.getMessage()); + } + return hash; + } +} diff --git a/springboot/src/main/java/com/sincre/springboot/controller/TuYaYunController.java b/springboot/src/main/java/com/sincre/springboot/controller/TuYaYunController.java new file mode 100644 index 0000000..a4b817f --- /dev/null +++ b/springboot/src/main/java/com/sincre/springboot/controller/TuYaYunController.java @@ -0,0 +1,188 @@ +package com.sincre.springboot.controller; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.sincre.springboot.ApiModel.*; +import com.sincre.springboot.ApiPlatform.TuYaCloudService; +import com.sincre.springboot.common.EhcacheUtil; +import com.sincre.springboot.utils.ApiHelper; +import io.swagger.annotations.Api; +import org.apache.commons.lang3.StringUtils; +import org.springframework.web.bind.annotation.*; + +import java.util.HashMap; +import java.util.Map; + +@RestController +@RequestMapping(value = "/TuYa/*") +@Api(value = "涂鸦云服务API调用") +public class TuYaYunController { + + @GetMapping("GetToken") + public TuYaResResult getTuYaToken(){ + + String apiUrl = "/v1.0/token?grant_type=1"; + Long t = System.currentTimeMillis(); + //Token获取前的签名 + String sign = TuYaCloudService.createSign(TuYaCloudService.ClientId+t,TuYaCloudService.Secret); + Map map = new HashMap(); + map.put("client_id", TuYaCloudService.ClientId); + map.put("sign",sign); + map.put("sign_method",TuYaCloudService.Sign_method); + map.put("t",t.toString()); + String result = ApiHelper.doGet(TuYaCloudService.TuYaOpenUrl + apiUrl,map); + + TuYaResResult resResult = new TuYaResResult<>(); + try{ + ObjectMapper objectMapper = new ObjectMapper(); + resResult = objectMapper.readValue(result,new TypeReference>(){}); + + String access_Token = resResult.getResult().getAccess_token(); //存储第一次获取的Token + EhcacheUtil ehcacheUtil = new EhcacheUtil(); + ehcacheUtil.setex("TuYa_Token",access_Token,60); + } catch(Exception ex){ + System.out.println(ex.getMessage()); + } + + return resResult; + } + + @GetMapping("GetDevicesInfo") + public TuYaResResult getTuYaDevicesInfo(){ + + EhcacheUtil ehcacheUtil = new EhcacheUtil(); + String apiUrl = "/v1.0/devices?device_ids="; + Long t = System.currentTimeMillis(); + String access_Token = ehcacheUtil.get("TuYa_Token"); + String sign = TuYaCloudService.createSign(TuYaCloudService.ClientId+access_Token+t,TuYaCloudService.Secret); + Map map = new HashMap(); + map.put("client_id", TuYaCloudService.ClientId); + map.put("access_token",access_Token); + map.put("sign",sign); + map.put("sign_method",TuYaCloudService.Sign_method); + map.put("t",t.toString()); + String result = ApiHelper.doGet(TuYaCloudService.TuYaOpenUrl + apiUrl,map); + + TuYaResResult resResult = null; + try{ + ObjectMapper objectMapper = new ObjectMapper(); + TypeReference> reference = new TypeReference>(){}; + resResult = objectMapper.readValue(result,reference); + System.out.println(resResult.getResult().total); + } catch(Exception ex){ + System.out.println(ex.getMessage()); + } + + System.out.println(result); + return resResult; + } + + + /** + * 根据schema分页获取开发者App下的用户列表 + * @param AppId 应用标识 + * @param pageIndex 页码 + * @param pageSize 大小 + * @return + */ + @GetMapping("{AppId}/GetTuYaAPPUser") + public String getTuYaAPPUser(@PathVariable("AppId") String AppId, @RequestParam int pageIndex, @RequestParam int pageSize){ + + EhcacheUtil ehcacheUtil = new EhcacheUtil(); + + String apiUrl = String.format("/v1.0/apps/%s/users?page_no=%d&page_size=%d",AppId,pageIndex,pageSize);//iotshunzhi + Long t = System.currentTimeMillis(); + String access_Token = ehcacheUtil.get("TuYa_Token"); + System.out.println(access_Token); + //Token获取后的签名 + String sign = TuYaCloudService.createSign(TuYaCloudService.ClientId+access_Token+t,TuYaCloudService.Secret); + Map headMap = new HashMap(); + headMap.put("client_id", TuYaCloudService.ClientId); + headMap.put("access_token",access_Token); + headMap.put("sign",sign); + headMap.put("sign_method",TuYaCloudService.Sign_method); + headMap.put("t",t.toString()); + + String result = ApiHelper.doGet(TuYaCloudService.TuYaOpenUrl + apiUrl,headMap); + + return result; + } + + + @PostMapping("{AppId}/AddTuYaAPPUser") + public String addTuYaAPPUser(@PathVariable("AppId") String AppId,@RequestBody UserInfo userInfo){ + + EhcacheUtil ehcacheUtil = new EhcacheUtil(); + + String apiUrl = String.format("/v1.0/apps/%s/user",AppId);//应用标识iotshunzhi + Long t = System.currentTimeMillis(); + String access_Token = ehcacheUtil.get("TuYa_Token"); + //Token获取后的签名 + String sign = TuYaCloudService.createSign(TuYaCloudService.ClientId+access_Token+t,TuYaCloudService.Secret); + Map headMap = new HashMap(); + headMap.put("client_id", TuYaCloudService.ClientId); + headMap.put("access_token",access_Token); + headMap.put("sign",sign); + headMap.put("sign_method",TuYaCloudService.Sign_method); + headMap.put("t",t.toString()); + + ObjectMapper objectMapper = new ObjectMapper(); + + String jsonResult = ""; + try { + jsonResult = objectMapper.writeValueAsString(userInfo); + System.out.println(jsonResult); + }catch (com.fasterxml.jackson.core.JsonProcessingException ex){ + ex.printStackTrace(); + } + + String result = ApiHelper.doPost(TuYaCloudService.TuYaOpenUrl + apiUrl,headMap,jsonResult); + + TuYaResResult resResult = null; + + return result; + } + + /** + * 生成配网的Token + * @return + */ + @GetMapping("AddDevicesToken") + public String addDevicesToken(@RequestParam String UId){ + + EhcacheUtil ehcacheUtil = new EhcacheUtil(); + + String apiUrl = String.format("/v1.0/devices/token"); + Long t = System.currentTimeMillis(); + String access_Token = ehcacheUtil.get("TuYa_Token"); + //Token获取后的签名 + String sign = TuYaCloudService.createSign(TuYaCloudService.ClientId+access_Token+t,TuYaCloudService.Secret); + System.out.println("签名"+sign); + Map map = new HashMap(); + map.put("client_id", TuYaCloudService.ClientId); + map.put("access_token",access_Token); + map.put("sign",sign); + map.put("sign_method",TuYaCloudService.Sign_method); + map.put("t",t.toString()); + + if(StringUtils.isNotBlank(UId)){ + UId = "ay1557735327941UvZAG"; + } + + ObjectMapper objectMapper = new ObjectMapper(); + DeviceToken deviceToken = new DeviceToken(); + deviceToken.setUid(UId); + deviceToken.setTimeZoneId("Asia/ZheJiang"); + + String jsonResult = ""; + try { + jsonResult = objectMapper.writeValueAsString(deviceToken); + System.out.println(jsonResult); + }catch (com.fasterxml.jackson.core.JsonProcessingException ex){ + ex.printStackTrace(); + } + String result = ApiHelper.doPost(TuYaCloudService.TuYaOpenUrl + apiUrl,map,jsonResult); + + return result; + } +} diff --git a/springboot/src/main/java/com/sincre/springboot/utils/ApiHelper.java b/springboot/src/main/java/com/sincre/springboot/utils/ApiHelper.java new file mode 100644 index 0000000..3df762c --- /dev/null +++ b/springboot/src/main/java/com/sincre/springboot/utils/ApiHelper.java @@ -0,0 +1,200 @@ +package com.sincre.springboot.utils; + +import org.apache.http.HttpEntity; +import org.apache.http.NameValuePair; +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.util.EntityUtils; + +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.util.*; + +public class ApiHelper { + + public static String doGet(String url,Map headerParamMap) { + CloseableHttpClient httpClient = null; + CloseableHttpResponse response = null; + String result = ""; + try { + // 通过址默认配置创建一个httpClient实例 + httpClient = HttpClients.createDefault(); + // 创建httpGet远程连接实例 + HttpGet httpGet = new HttpGet(url); + // 设置请求头信息, + for (Map.Entry entry : headerParamMap.entrySet()) { + httpGet.setHeader(entry.getKey(),entry.getValue()); + } + + // 设置配置请求参数 + RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 连接主机服务超时时间 + .setConnectionRequestTimeout(35000)// 请求超时时间 + .setSocketTimeout(60000)// 数据读取超时时间 + .build(); + // 为httpGet实例设置配置 + httpGet.setConfig(requestConfig); + // 执行get请求得到返回对象 + response = httpClient.execute(httpGet); + // 通过返回对象获取返回数据 + HttpEntity entity = response.getEntity(); + // 通过EntityUtils中的toString方法将结果转换为字符串 + result = EntityUtils.toString(entity); + } catch (ClientProtocolException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } finally { + // 关闭资源 + if (null != response) { + try { + response.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + if (null != httpClient) { + try { + httpClient.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + return result; + } + + /** + * 表单格式的post请求 + * @param url 接口地址 + * @param headerParamMap 设置请求头 + * @param paramMap 设置请求值 + * @return + */ + public static String doPost(String url,Map headerParamMap, Map paramMap) { + CloseableHttpClient httpClient ; + String result; + // 创建httpClient实例 + httpClient = HttpClients.createDefault(); + // 创建httpPost远程连接实例 + HttpPost httpPost = new HttpPost(url); + // 设置请求头 + httpPost.addHeader("Content-Type", "application/json"); + for (Map.Entry entry : headerParamMap.entrySet()) { + httpPost.setHeader(entry.getKey(),entry.getValue()); + } + // 配置请求参数实例 + RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 设置连接主机服务超时时间 + .setConnectionRequestTimeout(35000)// 设置连接请求超时时间 + .setSocketTimeout(60000)// 设置读取数据连接超时时间 + .build(); + // 为httpPost实例设置配置 + httpPost.setConfig(requestConfig); + + // 封装post请求参数 + if (null != paramMap && paramMap.size() > 0) { + List nvps = new ArrayList(); + // 通过map集成entrySet方法获取entity + Set> entrySet = paramMap.entrySet(); + // 循环遍历,获取迭代器 + Iterator> iterator = entrySet.iterator(); + while (iterator.hasNext()) { + Map.Entry mapEntry = iterator.next(); + nvps.add(new BasicNameValuePair(mapEntry.getKey(), mapEntry.getValue().toString())); + } + + // 为httpPost设置封装好的请求参数 + try { + UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nvps, "UTF-8"); + entity.setContentType("application/json"); + httpPost.setEntity(entity); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + } + result = closeHttpAndResult(httpClient,httpPost); + return result; + } + + /** + * post请求,内容体比较灵活,任意字符串格式的内容 + * @param url + * @param headerParamMap + * @param jsonParam + * @return + */ + public static String doPost(String url, Map headerParamMap, String jsonParam) { + CloseableHttpClient httpClient; +// CloseableHttpResponse httpResponse = null; + String result; + // 创建httpClient实例 + httpClient = HttpClients.createDefault(); + // 创建httpPost远程连接实例 + HttpPost httpPost = new HttpPost(url); + // 设置请求头 + httpPost.addHeader("Content-Type", "application/json"); + for (Map.Entry entry : headerParamMap.entrySet()) { + httpPost.setHeader(entry.getKey(),entry.getValue()); + } + // 配置请求参数实例 + RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 设置连接主机服务超时时间 + .setConnectionRequestTimeout(35000)// 设置连接请求超时时间 + .setSocketTimeout(60000)// 设置读取数据连接超时时间 + .build(); + // 为httpPost实例设置配置 + httpPost.setConfig(requestConfig); +// try { + StringEntity stringEntity = new StringEntity(jsonParam, ContentType.create("application/json","UTF-8")); +// stringEntity.setContentType("application/json"); +// stringEntity.setContentEncoding("gzip");//请求头的编码格式 + httpPost.setEntity(stringEntity); +// }catch (UnsupportedEncodingException e){ +// e.printStackTrace(); +// } + result = closeHttpAndResult(httpClient,httpPost); + return result; + } + + private static String closeHttpAndResult(CloseableHttpClient httpClient,HttpPost httpPost){ + CloseableHttpResponse httpResponse = null; + String result = null; + try { + // httpClient对象执行post请求,并返回响应参数对象 + httpResponse = httpClient.execute(httpPost); + // 从响应对象中获取响应内容 + HttpEntity entity = httpResponse.getEntity(); + result = EntityUtils.toString(entity); + } catch (ClientProtocolException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } finally { + // 关闭资源 + if (null != httpResponse) { + try { + httpResponse.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + if (null != httpClient) { + try { + httpClient.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + return result; + } +} + -- libgit2 0.21.0