package com.chenyun.cloud.utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chenyun.cloud.config.MyX509TrustManager;
import com.chenyun.cloud.constant.WeixinConstant;
import com.google.gson.Gson;
/**
* 创建时间:2019年3月19日 下午3:47:54
* 项目名称:chenyun-cloud-hello-service
* 类说明:
* @author guobinhui
* @since JDK 1.8.0_51
*/
public class WeiXinUtil {
private final static Logger logger= LoggerFactory.getLogger(WeiXinUtil.class);
public static JSONObject HttpGet(String URL) {
String result = null;
JSONObject jsonObj = null;
CloseableHttpClient httpclient = HttpClients.createDefault();
CloseableHttpResponse response = null;
try {
// 创建httpGet.
HttpGet httpGet = new HttpGet(URL);
// 通过请求对象获取响应对象
response = httpclient.execute(httpGet);
// 判断网络连接状态码是否正常(0--200都数正常)
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();//从HttpResponse中获取结果
if(!StringUtils.isEmpty(entity)){
result = EntityUtils.toString(entity,"utf-8");
logger.info("请求的数据结果为{}",result);
jsonObj = JSONObject.parseObject(result);//字符串类型转换为JSON对象
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return jsonObj;
}
public static Map <String,Object> cacheTokenAndTicket() throws IOException {
Gson gson = new Gson();
Map <String,Object> map = new HashMap <String,Object> ();
String token = null;
String ticket = null;
JSONObject tokenObj = null; //需要获取的access_token对象;
JSONObject ticketObj = null;//需要获取的jsapi_ticket对象;
System.out.println(System.getProperty("user.dir"));
String filePath = System.getProperty("user.dir")+"/src/main/resources/static/token.txt";
// String filePath = "C:/application/token.txt";
File file = new File(filePath);//Access_token保存的位置
if (!file.exists())
file.createNewFile();
// 如果文件大小等于0,说明第一次使用,存入Access_token
if (file.length() == 0) {
tokenObj = WeiXinUtil.getToken();
token = (String)tokenObj.get("access_token");
FileOutputStream fos = new FileOutputStream(filePath, false);// 不允许追加
tokenObj.put("expires_in",System.currentTimeMillis()/1000+"");
String json = gson.toJson(tokenObj);
fos.write(json.getBytes());
fos.close();
}else {
//读取文件内容
@SuppressWarnings("resource")
FileInputStream fis = new FileInputStream(file);
byte[] b = new byte[2048];
int len = fis.read(b);
String jsonAccess_token = new String(b, 0, len);// 读取到的文件内容
JSONObject access_token = gson.fromJson(jsonAccess_token,JSONObject.class);
if (access_token.get("expires_in") != null) {
String lastSaveTime = (String)access_token.get("expires_in");
long nowTime = System.currentTimeMillis()/1000;
long remianTime = nowTime - Long.valueOf(lastSaveTime);
if (remianTime < WeixinConstant.EXPIRESIN_TIME) {
JSONObject access = gson.fromJson(jsonAccess_token,JSONObject.class);
token = (String)access.get("access_token");
} else {
tokenObj = WeiXinUtil.getToken();
FileOutputStream fos = new FileOutputStream(file, false);// 不允许追加
tokenObj.put("expires_in",System.currentTimeMillis()/1000+"");
String json = gson.toJson(tokenObj);
fos.write((json).getBytes());
fos.close();
}
}
}
map.put("access_token",token);
map.put("jsapi_ticket",ticket);
return map;
}
/**
* 此处通过appid和appaecret获取的公众号调用凭证access_token用于生成js_ticket
*/
public static JSONObject getToken()throws IOException{
String url = WeixinConstant.GET_ACCESS_TOKEN.replace("APPID",WeixinConstant.APPID).replace("APPSECRET",WeixinConstant.APPSECRET);
JSONObject tokenObj = HttpGet(url);
return tokenObj;
}
/**
* 此处通过code获取的access_token用于公众号网页授权
*/
public static JSONObject getAccessToken(String code) throws IOException{
String host = "http://127.0.0.1:9001/home";
String url = WeixinConstant.ACCESS_TOKEN_URL.replace("APPID",WeixinConstant.APPID).replace("REDIRECT_URI",host).replace("CODE",code);
JSONObject AccessToken = HttpGet(url);
return AccessToken;
}
public static JSONObject getJsTicket(String access_token) throws IOException{
String url = WeixinConstant.TICKET_CREATE_URL.replace("ACCESS_TOKEN",access_token);
JSONObject ticketObj = HttpGet(url);
return ticketObj;
}
public static void main(String args[]) throws IOException {
cacheTokenAndTicket();
}
public static JSONObject httpPost(String requestUrl, String requestMethod, String outputStr) {
JSONObject jsonObject = null;
StringBuffer buffer = new StringBuffer();
try {
// 创建SSLContext对象,并使用我们指定的信任管理器初始化
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(requestUrl);
HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
httpUrlConn.setSSLSocketFactory(ssf);
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
// 设置请求方式(GET/POST)
httpUrlConn.setRequestMethod(requestMethod);
// 当有数据需要提交时
if (null != outputStr) {
OutputStream outputStream = httpUrlConn.getOutputStream();
// 注意编码格式,防止中文乱码
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
// 将返回的输入流转换成字符串
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = n