code是用户登录小程序产生的;wx_appid、wx_secret是小程序开放管理平台的参数。
@Controller
@RequestMapping("/wx")
public class WxController {
private final static String WX_APPID = "xxx";
private final static String WX_SECRET = "xxxx";
private final static String WX_GRANT_TYPE = "authorization_code";
/**
* 获取微信用户的openID
* @param code
* @return
*/
@RequestMapping("/getOpenId")
@ResponseBody
public Map<String,Object> getOpenId(String code){
System.out.println("code参数:"+code);
BufferedReader in = null;
Map<String,Object> map = new HashMap<>();
String url = "https://api.weixin.qq.com/sns/jscode2session?appid="
+WX_APPID+"&secret="+WX_SECRET+"&js_code="+code+"&grant_type="+WX_GRANT_TYPE;
try{
URL weChatUrl = new URL(url);
URLConnection conn = weChatUrl.openConnection();
// 设置通用的请求属性
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
// 建立实际的连接
conn.connect();
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer sb = new StringBuffer();
String line;
while ((line = in.readLine()) != null) {
sb.append(line);
}
System.out.println("获取的参数:"+sb.toString());
map.put("status",200 );
map.put("msg",sb.toString() );
}catch (Exception e){
e.printStackTrace();
}
return map;
}
}