微信公众号开发
//获取网络授权网址 public static final String url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect"; //获取微信openId public static final String RECEIVE_OPENID="https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
示范获取openid的案例
public String boosLookCustomer() throws IOException, Exception{
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
//定义一个openid
String openId = "";
//回调获取微信公众号的CODE
String url=CommonUtil.url;
//项目的路径http://localhost:8080/SSH04/
String urlProperties = CommonUtil.domainName;
//参数
String str = request.getParameter("str");
//拼接路径
String strUrl=urlProperties+"WxAction_boosLookCustomer.action?str="+str;
//判断传来的值是不是空
String agent = request.getHeader("User-Agent");
if(agent!=null){
String code=request.getParameter("code");
String state=request.getParameter("state");
if(code!=null && state!=null && "1".equals(state)){
//获取code以后调用获取openId
String openIdUrl=CommonUtil.RECEIVE_OPENID.replace("APPID", CommonUtil.APPID).replace("SECRET", CommonUtil.SECRET).replace("CODE", code);
//请求获取openID json串
String json=CommonUtil.sendGet(openIdUrl);
//解析
JSONObject jsonObject = new JSONObject(json);
String jsonObjectStr=jsonObject.toString();
if(jsonObjectStr.indexOf("openid")==-1){
openId = (String)request.getSession().getAttribute("openId");
}else if(jsonObject.getString("openid")!=null && !"".equals(jsonObject.getString("openid"))){
openId=jsonObject.getString("openid");
HttpSession session=request.getSession();
session.setAttribute("openId", openId);
session.setAttribute("third_openid", openId);
}else {
System.out.println("openid是空的");
}
System.out.println("Openid是:"+openId);
//以下获取openID后往下写逻辑
}else{
//回调微信网址,返回code
url=url.replace("APPID", CommonUtil.APPID).replace("REDIRECT_URI", URLEncoder.encode(strUrl, "UTF-8")).replace("SCOPE", "snsapi_base").replace("STATE", "1");
System.out.println("第一次回滚地址:"+url);
response.sendRedirect(url);
}
}
return null;
}
请求方法
public static String sendGet(String openIdUrl) {
HttpGet get = null;
CloseableHttpResponse resp = null;
CloseableHttpClient client = null;
try {
client = HttpClients.createDefault();
get = new HttpGet(openIdUrl);
resp = client.execute(get);
int statusCode = resp.getStatusLine().getStatusCode();
if(statusCode>=200&&statusCode<300) {
HttpEntity entity = resp.getEntity();
String content = EntityUtils.toString(entity,"utf-8");
return content;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(resp!=null) resp.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(client!=null) client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
哒哒哒哒哒哒哒哒哒哒哒哒哒哒哒哒哒哒哒哒哒哒哒哒

浙公网安备 33010602011771号