Controller层代码
package com.tm.ethereum.controller;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import com.tm.ethereum.contants.WebConstants;
import com.tm.ethereum.dao.AnaphylaxisLibDao;
import com.tm.ethereum.dao.DrugInfoDao;
import com.tm.ethereum.dao.HotSearchInfoDao;
import com.tm.ethereum.dao.VaccineNameDao;
import com.tm.ethereum.enums.DrugStatusEnum;
import com.tm.ethereum.model.AnaphylaxisLib;
import com.tm.ethereum.model.DrugInfo;
import com.tm.ethereum.model.HotSearchInfo;
import com.tm.ethereum.model.ResObject;
import com.tm.ethereum.model.VaccineName;
import com.tm.ethereum.util.CommonUtil;
import com.tm.ethereum.util.Constant;
import com.tm.ethereum.util.HttpUtils;
@RestController
public class AppController {
private static final Logger logger=LoggerFactory.getLogger(AppController.class);
@GetMapping("/app/getOpenId") // 获取用户信息
public ResObject<Object> getOpenId(String code) {
logger.info("getOpenId,code:{}",new Object[]{code});
ResObject<Object> object = new ResObject<Object>(Constant.Code_SUCCESS, Constant.SUCCESS, null, null);
String WX_URL = "https://api.weixin.qq.com/sns/jscode2session?appid="+ systemInfo.getWxAppid()+"&secret="+systemInfo.getWxSecret()+"&js_code="+code+"&grant_type=authorization_code";
try {
if (StringUtils.isBlank(code)) {
System.out.println("code为空");
} else {
/*String requestUrl = WX_URL.replace("APPID", SystemInfo.getWxAppid()).replace("SECRET", SystemInfo.getWxSecret())
.replace("JSCODE", code).replace("authorization_code", "authorization_code");*/
logger.info("getOpenId,WX_URL:{}",new Object[]{WX_URL});
JSONObject jsonObject = CommonUtil.httpsRequest(WX_URL, "GET", null);
logger.info("getOpenId,response:{}",new Object[]{jsonObject});
if (jsonObject != null) {
try {
object.setResObject(jsonObject);
// 业务操作
String openid = jsonObject.getString("openid");
if(WebConstants.ACCESS_TOKEN==null){
JSONObject obj=HttpUtils.drugLibAuth(systemInfo.getDrugLibUrlAuth(), systemInfo.getDrugLibAppid(), systemInfo.getDrugLibSecret());
logger.info("getOpenId,drugLibAuth obj:{}",new Object[]{obj});
if(obj!=null&&obj.containsKey("access_token")){
WebConstants.ACCESS_TOKEN=obj.getString("access_token");
}
}
jsonObject.put("access_token", WebConstants.ACCESS_TOKEN);
jsonObject.put("drugQueryUrl",systemInfo.getDrugLibUrlDrugQuery()+ WebConstants.ACCESS_TOKEN);
// wechatService.selectUserByOpenId(openid, headurl, nickname, sex, country, province, city);
// return openid;
} catch (Exception e) {
logger.info("业务操作失败",e);
}
} else {
logger.info("code:{}。无效",new Object[]{code});
return new ResObject<Object>(Constant.Code_FAIL, "code无效", null, null);
}
}
} catch (Exception e) {
return new ResObject<Object>(Constant.Code_FAIL, "登录发生异常", null, null);
}
return object;
}
}
工具类CommonUtil
package com.tm.ethereum.util;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import net.sf.json.JSONObject;
public class CommonUtil {
/**
* 发送https请求
* @param requestUrl 请求地址
* @param requestMethod 请求方式(GET、POST)
* @param outputStr 提交的数据
* @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
*/
public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {
JSONObject jsonObject = null;
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 conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(ssf);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
// 设置请求方式(GET/POST)
conn.setRequestMethod(requestMethod);
// 当outputStr不为null时向输出流写数据
if (null != outputStr) {
OutputStream outputStream = conn.getOutputStream();
// 注意编码格式
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
// 从输入流读取返回内容
InputStream inputStream = conn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
StringBuffer buffer = new StringBuffer();
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
// 释放资源
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
inputStream = null;
conn.disconnect();
jsonObject = JSONObject.fromObject(buffer.toString());
} catch (ConnectException ce) {
System.out.println("连接超时");
ce.printStackTrace();
} catch (Exception e) {
System.out.println("请求异常");
e.printStackTrace();
}
return jsonObject;
}
}
工具类MyX509TrustManager
package com.tm.ethereum.util;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
/**
* 类名: MyX509TrustManager.java</br>
* 描述: 信任管理器</br>
* 开发人员:wangl</br>
* 创建时间: 2018-01-09</br>
*/
public class MyX509TrustManager implements X509TrustManager {
// 检查客户端证书
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
// 检查服务器端证书
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
// 返回受信任的X509证书数组
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
注添加maven依赖是发现alibaba引入的json冲突
可使用一下依赖方式解决
解决方案:
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>