最近公司要开发小程序,由于业务需要,需要在用户注册时获取用户的openId作为userId进行注册
一、获取code
将code作为参数传递过来
//如果有code,说明是微信小程序,根据code获取openId
//classify用于标识是哪个小程序
if (!CheckUtil.checkNulls( keUser.getCode(),keUser.getClassify())){
//
String openid = OpenIdUtil.oauth2GetOpenid(keUser.getCode(),keUser.getClassify());
printParamsLog(openid, logger);
keUser.setUserId(openid);
}
二、工具类
package com.util; import net.sf.json.JSONObject; import org.apache.http.client.HttpClient; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.DefaultHttpClient; import java.util.HashMap; import java.util.Map; /** * @author xsx */ public class OpenIdUtil { public static String oauth2GetOpenid(String code,String classify) { String appid=""; String appsecret=""; switch (classify){ case "1": //自己的配置appid appid = "**********"; //自己的配置APPSECRET; appsecret = "**********"; break; case "2": appid = "**********"; appsecret = "************"; 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 = HttpUtil.get(requestUrl, params); //解析相应内容(转换成json对象) JSONObject json = JSONObject.fromObject(data); //用户的唯一标识(openid) String Openid =String.valueOf(json.get("openid")); //System.out.println(Openid); return Openid; } }
三、发送请求的工具类
package com.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 xsx */ public class HttpUtil { /** * 向指定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; } }
四、检查参数是否为空的工具类
public class CheckUtil { /** * 验证是否有空值的参数,只要有一个,就返回true * * @param args * @return true */ public static boolean checkNulls(String... args) { if (args.length == 0) { return true; } // for (String str : args) { if (isNullOrEmpty(str)) { return true; } } return false; } }