目 录CONTENT

文章目录

H5获取公众号OPENID方法

芈亓
2022-03-11 / 0 评论 / 0 点赞 / 51 阅读 / 3,284 字 / 正在检测是否收录...
温馨提示:
本文最后更新于 2022-04-12,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

获取openId方法,其中code是自动获取的,此文运行后就会获取用户的openId

@RequestMapping(value="/openIdMsg",produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
	@ResponseBody
	public void openIdMsg(HttpServletRequest request,HttpServletResponse response) throws IOException{
		Map<String, Object> map = new HashMap<String, Object>();
		String redirect_uri=URLEncoder.encode("https://www.mfzhosp.com/mkkMoblie/accessToken/WxOpenIdServlet, "UTF-8");
		StringBuffer url=new StringBuffer("https://open.weixin.qq.com/connect/oauth2/authorize?redirect_uri="+redirect_uri+
				"&appid=这里写自己公众号的appid&response_type=code&scope=snsapi_base&state=1#wechat_redirect");
		response.sendRedirect(url.toString());
	}
	
	@RequestMapping(value="/WxOpenIdServlet",produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
	@ResponseBody
	public String WxOpenIdServlet(HttpServletRequest request,HttpServletResponse response){
		Map<String, Object> map = new HashMap<String, Object>();
		String code = request.getParameter("code");
		if (!isNull(code)) {
			map.put("type", false);
			map.put("massage", "未获取到code");
			return JsonMapper.getInstance().toJson(map);
		}
		Map params = new HashMap();
		params.put("secret", ""); // 公众号密钥
		params.put("appid", "");  // 公众号appid
		params.put("grant_type", "authorization_code");
		params.put("code", code);
		String result = HttpGetUtil.httpRequestToString(
				"https://api.weixin.qq.com/sns/oauth2/access_token", params);
		JSONObject jsonObject = JSONObject.fromObject(result);
 
		String openid = jsonObject.get("openid").toString();
		map.put("openId", openid);
		System.out.println("得到的openid为:"+openid);
		return JsonMapper.getInstance().toJson(map);
	}

HttpGetUtil中代码,如自己有也可以使用自己的类添加如下方法即可。

public static String httpRequestToString(String url, 
			Map<String,String> params) {
		String result = null;
		try {
			InputStream is = httpRequestToStream(url,  params);
			BufferedReader in = new BufferedReader(new InputStreamReader(is,"UTF-8"));
			StringBuffer buffer = new StringBuffer();
			String line = "";
			while ((line = in.readLine()) != null) {
				buffer.append(line);
			}
			result = buffer.toString();
		} catch (Exception e) {
			return null;
		}
		return result;
	}
 
	private static InputStream httpRequestToStream(String url,
			Map<String, String> params) {
		 InputStream is = null;
	        try {
	            String parameters = "";
	            boolean hasParams = false;
	            for(String key : params.keySet()){
	                String value = URLEncoder.encode(params.get(key), "UTF-8");
	                parameters += key +"="+ value +"&";
	                hasParams = true;
	            }
	            if(hasParams){
	                parameters = parameters.substring(0, parameters.length()-1);
	            }
 
 
	                url += "?"+ parameters;
	          
	            URL u = new URL(url);
	            HttpURLConnection conn = (HttpURLConnection) u.openConnection();
				conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
				conn.setRequestProperty("Accept-Charset", "UTF-8");
				conn.setRequestProperty("contentType", "utf-8");
	            conn.setConnectTimeout(50000);  
	            conn.setReadTimeout(50000);
	            conn.setDoInput(true);
	            //设置请求方式,默认为GET
	            conn.setRequestMethod("GET");
 
 
	            is = conn.getInputStream();
	        } catch (UnsupportedEncodingException e) {
	            e.printStackTrace();
	        } catch (MalformedURLException e) {
	            e.printStackTrace();
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
	        return is;
	}
0

评论区