您的当前位置:首页正文

java 请求微信https接口

2024-11-09 来源:个人技术集锦

最近在做微信小程序的时候获取小程序的openid和session_key 请求的接口时https协议的。但是请求https协议是需要ssl证书的,在网上看了很多方法 看到了一个跳过ssl校验的方法  如下:

小程序端:

 wx.getUserInfo({
            success: function(res) {
              var iv = res.iv;//这是微信加密算法的初始向量
              var encryptedData = res.encryptedData;//加密数据
              
              // 用户已经授权过,不需要显示授权页面,所以不需要改变 isHide 的值
              // 根据自己的需求有其他操作再补充
              // 我这里实现的是在用户授权成功后,调用微信的 wx.login 接口,从而获取code
              wx.login({
                success: res => {
                  // 获取到用户的 code 之后:res.code
                  console.log("用户的code:" + res.code);
                  // 可以传给后台,再经过解析获取用户的 openid
                  // 或者可以直接使用微信的提供的接口直接获取 openid ,方法如下:
                  wx.request({
                    // 自行补上自己的 APPID 和 SECRET
                    url: 'http://localhost:8080/xxx/xxx/xxx.do',//后端方法
                    header: {
                      'content-type': 'application/x-www-form-urlencoded'
                    },
                    data: {
                      encryptedData: encryptedData, iv: iv, code: res.code
                    },
                    success: res => {
                      // 获取到用户的 openid
                      console.log( res.data.userInfo);
                    }
                  });
                }
              });
            }
          });

java后端

//controller层
@RequestMapping("login.do")
	@ResponseBody
	public Map<String, Object> getUserInfo2(String encryptedData, String iv, String code) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		if (code == null || code.length() == 0) {
			map.put("status", 0);
			map.put("msg", "code 不能为空");
		}

		HttpsRequest httpsRequest = new HttpsRequest();//实例化工具类

		String appId = "wx16454ab456a69c0b";
		String appSecret = "9802c50d49a2f0416fecc388ded409a8";
		String grant_type = "authorization_code";
		String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId + "&secret=" + appSecret
				+ "&js_code=" + code + "&grant_type=" + grant_type + "";
		String s = httpsRequest.httpsRequest(url, "GET", null);//调用工具类发起https请求
		JSONObject jsonObject = JSONObject.parseObject(s);//转为jsonObject
		String session_key = jsonObject.get("session_key").toString();

		String result = AesCbcUtil.decrypt(encryptedData, session_key, iv, "UTF-8");//调用解密算法
		if (null != result && result.length() > 0) {
			map.put("status", 1);
			map.put("msg", "解密成功");

			JSONObject userInfoJSON = JSONObject.parseObject(result);

			Map<String, Object> userInfo = new HashMap<String, Object>();
			userInfo.put("openId", userInfoJSON.get("openId"));
			userInfo.put("nickName", userInfoJSON.get("nickName"));
			userInfo.put("gender", userInfoJSON.get("gender"));
			userInfo.put("city", userInfoJSON.get("city"));
			userInfo.put("province", userInfoJSON.get("province"));
			userInfo.put("country", userInfoJSON.get("country"));
			userInfo.put("avatarUrl", userInfoJSON.get("avatarUrl"));
			userInfo.put("unionId", userInfoJSON.get("unionId"));
			map.put("userInfo", userInfo);
			System.out.println(map.get("userInfo"));
			return map;

		}
		map.put("status", 0);
		map.put("msg", "解密失败");
		return map;
	}
//发起https请求
public class HttpsRequest {

	/*
	 * 处理https GET/POST请求 请求地址、请求方法、参数
	 */
	public String httpsRequest(String requestUrl, String requestMethod, String outputStr) {
		StringBuffer buffer = null;
		try {
			// 创建SSLContext
			SSLContext sslContext = SSLContext.getInstance("SSL");
			TrustManager[] tm = { new MyX509TrustManager() };
			// 初始化
			sslContext.init(null, tm, new java.security.SecureRandom());
			;
			// 获取SSLSocketFactory对象
			SSLSocketFactory ssf = sslContext.getSocketFactory();
			URL url = new URL(requestUrl);
			HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.setRequestMethod(requestMethod);
			// 设置当前实例使用的SSLSoctetFactory
			conn.setSSLSocketFactory(ssf);
			conn.connect();
			// 往服务器端写内容
			if (null != outputStr) {
				OutputStream os = conn.getOutputStream();
				os.write(outputStr.getBytes("utf-8"));
				os.close();
			}

			// 读取服务器端返回的内容
			InputStream is = conn.getInputStream();
			InputStreamReader isr = new InputStreamReader(is, "utf-8");
			BufferedReader br = new BufferedReader(isr);
			buffer = new StringBuffer();
			String line = null;
			while ((line = br.readLine()) != null) {
				buffer.append(line);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return buffer.toString();
	}
	
}
//这个可以跳过证书校验
public class MyX509TrustManager implements X509TrustManager {

	@Override
	public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public X509Certificate[] getAcceptedIssuers() {
		// TODO Auto-generated method stub
		return null;
	}

}

 

 

  

//解密算法

public class AesCbcUtil {

	static {
		// BouncyCastle是一个开源的加解密解决方案,
		Security.addProvider(new BouncyCastleProvider());
	}

	/**
	 * AES解密
	 *
	 * @param data           //密文,被加密的数据
	 * @param key            //秘钥
	 * @param iv             //偏移量
	 * @param encodingFormat //解密后的结果需要进行的编码
	 * @return
	 * @throws Exception
	 */
	public static String decrypt(String data, String key, String iv, String encodingFormat) throws Exception {
		//initialize();

		// 被加密的数据
		byte[] dataByte = Base64.decodeBase64(data.getBytes());
		// 加密秘钥
		byte[] keyByte = Base64.decodeBase64(key.getBytes());
		// 偏移量
		byte[] ivByte = Base64.decodeBase64(iv.getBytes());
		//URLEncoder.encode(iv,"UTF-8").replace("%3D","=").replace("%2F","/");

		try {
			Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");

			SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");

			AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
			parameters.init(new IvParameterSpec(ivByte));

			cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化

			byte[] resultByte = cipher.doFinal(dataByte);
			if (null != resultByte && resultByte.length > 0) {
				String result = new String(resultByte, encodingFormat);
				return result;
			}
			return null;
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (InvalidParameterSpecException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (InvalidAlgorithmParameterException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		return null;
	}

}

 

转jsonObject的时候需要几个包

<dependency>
			<groupId>org.codehaus.xfire</groupId>
			<artifactId>xfire-core</artifactId>
			<version>1.2.6</version>
		</dependency>
		<dependency>
			<groupId>org.bouncycastle</groupId>
			<artifactId>bcprov-jdk15on</artifactId>
			<version>1.60</version>
		</dependency>

		<dependency>
			<groupId>commons-beanutils</groupId>
			<artifactId>commons-beanutils</artifactId>
			<version>1.9.3</version>
		</dependency>
		<dependency>
			<groupId>commons-collections</groupId>
			<artifactId>commons-collections</artifactId>
			<version>3.2.1</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/commons-lang/commons-lang -->
		<dependency>
			<groupId>commons-lang</groupId>
			<artifactId>commons-lang</artifactId>
			<version>2.6</version>
		</dependency>
		<dependency>
			<groupId>commons-logging</groupId>
			<artifactId>commons-logging</artifactId>
			<version>1.2</version>
		</dependency>
		<dependency>
			<groupId>net.sf.ezmorph</groupId>
			<artifactId>ezmorph</artifactId>
			<version>1.0.6</version>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.68</version>
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.5.8</version>
		</dependency>
		<dependency>
			<groupId>net.sf.json-lib</groupId>
			<artifactId>json-lib</artifactId>
			<version>2.2.3</version>
			<classifier>jdk15</classifier><!-- jdk版本 -->
		</dependency>

 

 这是几个比较主要的包  其中的json-lib包是个坑啊   必须要加<classifier>jdk15</classifier>  不然的话maven依赖 死活找不到它

 

显示全文