import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import javax.servlet.http.HttpServletRequest; import net.sf.json.JSONObject; import org.springframework.web.bind.annotation.RequestMapping; public class Ty { /*** * V型知识库 www.vxzsk.com * @param request * @return */ @RequestMapping(value="/xx") public String getUserOpenid(HttpServletRequest request){ System.out.println("获取的code::::"+request.getParameter("code")); String appid = "应用id"; String secret = "应用秘钥"; String code=request.getParameter("code"); String weiUserJson=this.sendGet("https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appid+"&secret="+secret+"&code="+code+"&grant_type=authorization_code", "utf-8", 30000); JSONObject jsonOuth = JSONObject.fromObject(weiUserJson); String openid= jsonOuth.getString("openid"); System.out.println("openid:"+openid); return "xx"; } /*** * 模拟get请求 * @param url * @param charset * @param timeout * @return */ public static String sendGet(String url, String charset, int timeout) { String result = ""; try { URL u = new URL(url); try { URLConnection conn = u.openConnection(); conn.connect(); conn.setConnectTimeout(timeout); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset)); String line=""; while ((line = in.readLine()) != null) { result = result + line; } in.close(); } catch (IOException e) { return result; } } catch (MalformedURLException e) { return result; } return result; } }
自定义菜单json字符串设置
{
"name"
:
"网页授权"
,
"type"
:
"view"
,
"url"
:
"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxab1321a3sss28b&redirect_uri=http://www.xxxx.com/xxx项目名/weixin/xxx.do&response_type=code&scope=snsapi_base&state=1#wechat_redirect"
}