最近开发小程序,有的功能需要用到openid,微信官方又规定需要用到第三方服务器请求的模式,才可以拿到 openId,自己这里写了,仅供参考。
1.controller
package com.wct.shop.controller;
import com.wct.shop.util.CheckUtil;
import com.wct.shop.util.KeUser;
import com.wct.shop.util.OpenIdUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* @author :cijiancao
* @version :1.0.0
* @Date :2018/2/28 14:44
* @Description :
*/
@Controller
public class OpenidController {
@RequestMapping("/queryOpenid")
public @ResponseBody KeUser testUser(@RequestBody KeUser user) {
String openid = null;//openid
CheckUtil checkUtil = new CheckUtil();//判断是否为空对象
if (!checkUtil.checkNulls(user.getCode(), user.getClassify())) {
//
openid = OpenIdUtil.oauth2GetOpenid(user.getCode(), user.getClassify());//调用请求接口获取openid
user.setOpenId(openid);
}
return user;//返回user对象,包含openid对象
}
}
2.判断是否为空
package com.wct.shop.util;
import static com.mysql.jdbc.StringUtils.isNullOrEmpty;
/**
* @author :cijiancao
* @version :1.0.0
* @Date :2018/2/28 14:58
* @Description :
*/
public class CheckUtil {
/**
* 验证是否有空值的参数,只要有一个,就返回true
*
* @param args
* @return true
*/
public boolean checkNulls(String... args) {
if (args.length == 0) {
return true;
}
//
for (String str : args) {//遍历每个参数,判断是否为空
if (isNullOrEmpty(str)) {
return true;
}
}
return false;
}
}
3.配置小程序相关信息,调用获取openid的接口
package com.wct.shop.util;
import net.sf.json.JSONObject;
/**
* @author :cijiancao
* @version :1.0.0
* @Date :2018/2/28 14:49
* @Description :
*/
public class OpenIdUtil {
public static String oauth2GetOpenid(String code,String classify) {
String appid="";
String appsecret="";
//classify:用于区分不同的小程序
switch (classify){
case "1":
appid = "wx123";//手动配置小程序appid
appsecret = "123";//手动配置小程序appsecret
break;
case "2":
appid = "wx123";
appsecret = "123";
break;
case "3":
appid = "**********";
appsecret = "************";
break;
case "4":
appid = "**********";
appsecret = "************";
break;
case "5":
appid = "**********";
appsecret = "************";
}
//授权(必填)
String grant_type = "authorization_code";
//URL
String requestUrl = "https://api.weixin.qq.com/sns/jscode2session";
//请求参数
String params = "appid=" + appid + "&secret=" + appsecret + "&js_code=" + code + "&grant_type=" + grant_type;
//发送请求
String data = OpenIdHttpUtil.get(requestUrl, params);
//解析相应内容(转换成json对象)
JSONObject json = JSONObject.fromObject(data);
//用户的唯一标识(openid)
String Openid =String.valueOf(json.get("openid"));
//System.out.println(Openid);
return Openid;
}
}
4.用于发送请求
package com.wct.shop.util;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
/**
* @author :cijiancao
* @version :1.0.0
* @Date :2018/2/28 14:46
* @Description :
*/
public class OpenIdHttpUtil {
/**
* 向指定URL发送GET方法的请求
*
* @param url
* 发送请求的URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return String 所代表远程资源的响应结果
*/
public static String get(String url,String param){
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
//System.out.println(urlNameString);
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
/*for (String key : map.keySet()) {
System.out.println(key + "--->" + map.get(key));
}*/
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
}