Commit ded5e46f authored by 华润's avatar 华润

跨省单位开户鉴权认证请求第三方接口代码提交

parent ecc00e13
package net.cdkj.gjj.adapter.controller;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import net.cdkj.gjj.adapter.domain.Json;
import net.cdkj.gjj.adapter.domain.TimeExpiredPoolCache;
import org.springframework.web.bind.annotation.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Cache设置token缓存和获取类
*/
@RestController
@RequestMapping(value = "Cache")
public class CacheDemoController {
/**
* 将从第三方拿到的token值存入java内存中,并设置对应的过期时间
* @return
*/
@RequestMapping(value = "/saveToken", method = RequestMethod.GET)
public String saveToken() {
try {
//1.调用鉴权认证接口获取token值和过期时间的json字符串
String str = TokenAcquisitionController.TokenAcquisition();
Json jsonentity = JSONObject.parseObject(str, Json.class);
if(jsonentity!=null){
if(jsonentity.isResult()){
boolean result=jsonentity.isResult();
String access_token=jsonentity.getAccess_token();
Long expires_in=jsonentity.getExpires_in();
System.out.println("result:"+result+","+"token值:"+access_token+","+"有效时间:"+expires_in);
TimeExpiredPoolCache.getInstance().put("access_token",access_token, expires_in*1000L);
}
}
return "保存token进入缓冲成功";
} catch(Exception e){
return "保存token进入缓存失败";
}
}
/**
* 获取存入java内存中的token值
* @return
*/
@RequestMapping(value = "/getToken", method = RequestMethod.GET)
public String getToken(){
try {
String token = TimeExpiredPoolCache.getInstance().get("access_token");
if (null!=token){
return token;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
......@@ -3,12 +3,12 @@ package net.cdkj.gjj.adapter.controller;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import static net.cdkj.gjj.adapter.domain.GzipUtil.zipString;
import static net.cdkj.gjj.adapter.domain.GzipUtil.unzipString;
/**
* 鉴权认证控制类
......@@ -26,13 +26,15 @@ public class TokenAcquisitionController {
@ResponseBody
@PostMapping("token")
public static String TokenAcquisition() {
String resp = null;
JSONObject jsonObject = new JSONObject();
jsonObject.put("app_id", "111");
jsonObject.put("app_secret", "222");
jsonObject.put("grant_type", "127.0.0.1");
jsonObject.put("grant_type", "192.168.101.34");
jsonObject.put("userid", "gjj");
String str = jsonObject.toString();
System.out.println("发送给第三方的报文:" + str);
System.out.println("zip压缩处理之前要发送给第三方的报文:" + str);
String s = zipString(str);//进行zip压缩
System.out.println("zip压缩处理之后发送给第三方的报文:" + s);
StringBuffer sb = new StringBuffer();
HttpURLConnection conn = null;
OutputStream out = null;
......@@ -56,7 +58,7 @@ public class TokenAcquisitionController {
// 设置文件字符集:
conn.setRequestProperty("Charset", "UTF-8");
// 转换为字节数组
byte[] data = (str).getBytes("UTF-8");
byte[] data = (s).getBytes("UTF-8");
// 设置文件长度
conn.setRequestProperty("Content-Length", String.valueOf(data.length));
// 开始连接请求
......@@ -74,8 +76,10 @@ public class TokenAcquisitionController {
sb.append(readLine);
}
responseReader.close();
System.out.println("第三方返回的报文:" + sb.toString());
return sb.toString();
System.out.println("第三方返回的zip压缩过的报文:" + sb.toString());
String s1 = unzipString(sb.toString());//将第三方返回的压缩过的json字符串解压缩
System.out.println("第三方返回的zip解压缩之后的报文:" + s1);
return s1;
} else {
System.out.println("请求失败!!!");
}
......@@ -105,12 +109,35 @@ public class TokenAcquisitionController {
@ResponseBody
@PostMapping("token2")
public String TokenAcquisition2() {
String resp = null;
JSONObject jsonObject = new JSONObject();
jsonObject.put("expires_in", 60);
jsonObject.put("result", true);
jsonObject.put("expires_in", 30);
jsonObject.put("access_token", "skdfhskjdfhskjdfhskdfjhk");
String str = jsonObject.toString();
return jsonObject.toString();
//压缩处理
String s = zipString(str);
return s;
}
/**
* 测试json字符串zip压缩,解压缩
*
* @param
* @param
*/
@ResponseBody
@PostMapping("testzip")
public void testzip() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("app_id", "111");
jsonObject.put("app_secret", "222");
jsonObject.put("grant_type", "192.168.101.34");
jsonObject.put("userid", "gjj");
String str = jsonObject.toString();
System.out.println("未经过压缩处理的json字符串:"+str);
String s = zipString(str);//进行zip压缩
System.out.println("压缩处理之后的json字符串:"+s);
String s1 = unzipString(s);//进行zip解压缩
System.out.println("解压缩处理之后的json字符串:"+s1);
}
}
package net.cdkj.gjj.adapter.domain;
import org.springframework.util.StringUtils;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
public class GzipUtil {
/**
* 压缩
* @param unzip
* @return
*/
public static String zipString(String unzip) {
return new sun.misc.BASE64Encoder().encodeBuffer(zipByte(unzip));
}
/**
* 对cpspJson进行解压
* @param zip
* @return
*/
public static String unzipString(String zip) {
try {
byte[] decode = new sun.misc.BASE64Decoder().decodeBuffer(zip);
String unziqStr = unzipByte(decode);
//如果解压缩失败,返回原数据
if (StringUtils.isEmpty(unziqStr)){
return zip;
}
return unziqStr;
} catch (IOException ex) {
System.out.println("解压文件失败"+ex);
return zip;
}
}
public static String unzipString1(String zip) {
try {
byte[] decode = new sun.misc.BASE64Decoder().decodeBuffer(zip);
return unzipByte(decode);
} catch (IOException ex) {
System.out.println("解压文件失败"+ex);
return null;
}
}
/**
* 压缩
* @param unzip
* @return
*/
public static byte[] zipByte(String unzip) {
Deflater deflater = new Deflater(9);
deflater.setInput(unzip.getBytes());
deflater.finish();
final byte[] bytes = new byte[256];
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(256);
while (!deflater.finished()) {
int length = deflater.deflate(bytes);
outputStream.write(bytes, 0, length);
}
deflater.end();
return outputStream.toByteArray();
}
/**
* 解压缩
*
* @param decode
* @return
*/
public static String unzipByte(byte[] decode) {
Inflater inflater = new Inflater();
inflater.setInput(decode);
final byte[] bytes = new byte[256];
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(256);
try {
while (!inflater.finished()) {
int length = inflater.inflate(bytes);
outputStream.write(bytes, 0, length);
}
} catch (DataFormatException e) {
System.out.println("解压缩失败"+e);
return null;
} finally {
inflater.end();
}
return outputStream.toString();
}
}
......@@ -4,34 +4,40 @@ import java.util.Objects;
public class Json {
private String app_id;
// private String app_id;
//
// private String app_secret;
//
// private String grant_type;
private String app_secret;
private String access_token;
private String grant_type;
private Long expires_in;
public String getApp_id() {
return app_id;
private boolean result;
public String getAccess_token() {
return access_token;
}
public void setApp_id(String app_id) {
this.app_id = app_id;
public void setAccess_token(String access_token) {
this.access_token = access_token;
}
public String getApp_secret() {
return app_secret;
public Long getExpires_in() {
return expires_in;
}
public void setApp_secret(String app_secret) {
this.app_secret = app_secret;
public void setExpires_in(Long expires_in) {
this.expires_in = expires_in;
}
public String getGrant_type() {
return grant_type;
public boolean isResult() {
return result;
}
public void setGrant_type(String grant_type) {
this.grant_type = grant_type;
public void setResult(boolean result) {
this.result = result;
}
@Override
......@@ -39,13 +45,13 @@ public class Json {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Json json = (Json) o;
return Objects.equals(app_id, json.app_id) &&
Objects.equals(app_secret, json.app_secret) &&
Objects.equals(grant_type, json.grant_type);
return result == json.result &&
Objects.equals(access_token, json.access_token) &&
Objects.equals(expires_in, json.expires_in);
}
@Override
public int hashCode() {
return Objects.hash(app_id, app_secret, grant_type);
return Objects.hash(access_token, expires_in, result);
}
}
package net.cdkj.gjj.adapter.domain;
import java.util.LinkedList;
import java.util.List;
import java.util.Map.Entry;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
public class TimeExpiredPoolCache {
private static long defaultCachedMillis = 30 * 1000L;//过期时间默认10秒
private static long timerMillis = 30 * 1000L;//定时清理默认10秒
/**
* 对象池
*/
private static ConcurrentHashMap<String, DataWrapper<?>> dataPool = null;
/**
* 对象单例
*/
private static TimeExpiredPoolCache instance = null;
private TimeExpiredPoolCache() {
dataPool = new ConcurrentHashMap<String, DataWrapper<?>>();
}
private static synchronized void syncInit() {
if (instance == null) {
instance = new TimeExpiredPoolCache();
initTimer();
}
}
public static TimeExpiredPoolCache getInstance() {
if (instance == null) {
syncInit();
}
return instance;
}
/**
* 定时器定时清理过期缓存
*/
private static Timer timer = new Timer();
private static void initTimer() {
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
try {
clearExpiredCaches();
} catch (Exception e) {
//logger.error("clearExpiredCaches error.", e);
}
}
}, timerMillis, timerMillis);
}
/**
* 缓存数据
* @param key key值
* @param data 缓存数据
* @param cachedMillis 过期时间
* @param dataRenewer 刷新数据
* @return
*/
@SuppressWarnings("unchecked")
public <T> T put(String key, T data, long cachedMillis, DataRenewer<T> dataRenewer) throws Exception {
DataWrapper<T> dataWrapper = (DataWrapper<T>)dataPool.get(key);
if (data == null && dataRenewer != null) {
data = dataRenewer.renewData();
}
//当重新获取数据为空,直接返回不做put
if (data == null){
return null;
}
if (dataWrapper != null) {
//更新
dataWrapper.update(data, cachedMillis);
} else {
dataWrapper = new DataWrapper<T>(data, cachedMillis);
dataPool.put(key, dataWrapper);
}
return data;
}
/**
* 直接设置缓存值和时间
* @param key
* @param data
* @param cachedMillis
* @return
*/
@SuppressWarnings("unchecked")
public <T> T put(String key, T data, long cachedMillis) throws Exception{
DataWrapper<T> dataWrapper = (DataWrapper<T>)dataPool.get(key);
if (dataWrapper != null) {
//更新
dataWrapper.update(data, cachedMillis);
} else {
dataWrapper = new DataWrapper<T>(data, cachedMillis);
dataPool.put(key, dataWrapper);
}
return data;
}
/**
* 默认构造时间的缓存数据
* @param key
* @param data
* @param dataRenewer
* @return
*/
@Deprecated
public <T> T put(String key, T data, DataRenewer<T> dataRenewer) throws Exception {
return put(key, data, defaultCachedMillis, dataRenewer);
}
/**
* 获取缓存
* @param key
* @param cachedMillis
* @param dataRenewer
* @return
*/
@SuppressWarnings("unchecked")
public <T> T get(String key, long cachedMillis, DataRenewer<T> dataRenewer) throws Exception {
DataWrapper<T> dataWrapper = (DataWrapper<T>)dataPool.get(key);
if (dataWrapper != null && !dataWrapper.isExpired()) {
return dataWrapper.data;
}
return put(key, null, cachedMillis, dataRenewer);
}
@SuppressWarnings("unchecked")
public <T> T get(String key) throws Exception {
DataWrapper<T> dataWrapper = (DataWrapper<T>)dataPool.get(key);
if (dataWrapper != null && !dataWrapper.isExpired()) {
return dataWrapper.data;
}
return null;
}
/**
* 清除缓存
*/
public void clear() {
dataPool.clear();
}
/**
* 删除指定key的value
* */
public void remove(String key){
dataPool.remove(key);
}
/**
* 数据封装
*/
private class DataWrapper<T> {
/**
* 数据
*/
private T data;
/**
* 到期时间
*/
private long expiredTime;
/**
* 缓存时间
*/
private long cachedMillis;
private DataWrapper(T data, long cachedMillis) {
this.update(data, cachedMillis);
}
public void update(T data, long cachedMillis) {
this.data = data;
this.cachedMillis = cachedMillis;
this.updateExpiredTime();
}
public void updateExpiredTime() {
this.expiredTime = System.currentTimeMillis() + cachedMillis;
}
/**
* 数据是否过期
* @return
*/
public boolean isExpired() {
if (this.expiredTime > 0) {
return System.currentTimeMillis() > this.expiredTime;
}
return true;
}
}
/**
* 数据构造
*/
public interface DataRenewer<T> {
public T renewData();
}
/**
* 清除过期的缓存
*/
private static void clearExpiredCaches() {
List<String> expiredKeyList = new LinkedList<String>();
for(Entry<String, DataWrapper<?>> entry : dataPool.entrySet()){
if (entry.getValue().isExpired()) {
expiredKeyList.add(entry.getKey());
}
}
for (String key : expiredKeyList) {
dataPool.remove(key);
}
}
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment