第一句子网 - 唯美句子、句子迷、好句子大全
第一句子网 > JAVA 实现微信公众号菜单设置功能

JAVA 实现微信公众号菜单设置功能

时间:2020-05-29 01:30:10

相关推荐

JAVA 实现微信公众号菜单设置功能

接上前边微信的相关功能,本编实现的功能为使用JAVA代码设置微信公众号菜单。

package com.xxx.wechat;import java.util.ArrayList;import java.util.List;import com.mon.HttpConnectionUtil;import com.xxxx.util.json.JsonUtil;/*** 微信菜单发布工具类* @author xxxx* @date 8月15日 下午4:18:45* @version V1.0*/public class WechatMenuUtil {//private static Logger logger = LogManager.getLogger(WechatMenuUtil.class); //项目名称private final static String projectName = "wechat";//秘钥private final static String secret = "";//敏学习(edu_minxue)private final static String subPlatform = "prod";private final static String domainName = "";private final static String appid = "1234567";/*** 测试* @param args* @author xxx* @date 8月15日 下午4:00:33*/public static void main(String[] args) {try {String strMenu = WechatMenuUtil.updateWechatMenu();System.out.println("strMenu:"+strMenu);String access_token = WechatMenuUtil.getAccessToken(subPlatform);String url = "https://api./cgi-bin/menu/create?access_token="+access_token;String result = HttpConnectionUtil.AccessUrl(url, strMenu);System.out.println("result:" + result);} catch (OAuthException e) {System.out.println(e.getMessage());}}/*** 获取access_token* @return* @throws OAuthException*/private static String getAccessToken(String subPlatform) throws OAuthException{String access_token = null;if(subPlatform != null && !subPlatform.equals("")){String tokenUrl = "/WechatUtils_"+ subPlatform +"/initServlet.do";System.out.println("getAccess_token tokenUrl:" + tokenUrl);access_token = HttpConnectionUtil.AccessUrlGet(tokenUrl);System.out.println("getAccess_token access_token:" + access_token);}else{access_token = WechatMenuUtil.getAccessToken();}return access_token;}/*** 微信菜单* @return* @author xxx* @date 8月15日 下午3:42:04*/private static String updateWechatMenu(){//1WechatMenu menu1 = new WechatMenu();menu1.setType("view");menu1.setName("成绩");//menu1.setUrl("https://open./connect/oauth2/authorize?appid="+ appid +"&redirect_uri=http%3a%2f%2f"+ domainName +"%2f"+ projectName +"%2fwechatPaper%2festimateScore.do&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect");menu1.setUrl("http://"+ domainName +"/"+ projectName +"/estimateHome");//2WechatMenu menu2 = new WechatMenu();menu2.setType("view");menu2.setName("错题");//menu3.setUrl("https://open./connect/oauth2/authorize?appid="+ appid +"&redirect_uri=http%3a%2f%2f"+ domainName +"%2f"+ projectName +"%2fhomePage&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect");menu2.setUrl("http://"+ domainName +"/"+ projectName +"/LearnPaper");//3WechatMenu menu3 = new WechatMenu();menu3.setType("view");menu3.setName("扫一扫");//menu3.setUrl("https://open./connect/oauth2/authorize?appid="+ appid +"&redirect_uri=http%3a%2f%2f"+ domainName +"%2f"+ projectName +"%2fhomePage&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect");menu3.setUrl("http://"+ domainName +"/"+ projectName +"/homePage");//ALLList<WechatMenu> meunList = new ArrayList<WechatMenu>();meunList.add(menu3);meunList.add(menu2);meunList.add(menu1);//根节点WechatMenu menu = new WechatMenu();menu.setButton(meunList);String strMunu = JsonUtil.JavaBean2ToJson(menu);return strMunu;}//access_token 获取接口private final static String WECHAT_URL = "https://api./cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+secret;/*** 获取access_token* @return* @author xxxx* @date 8月20日 上午11:50:54*/private static String getAccessToken() {String access_token = null;try{System.out.println("getAccessToken i(ss):" );//获取access_tokenString accessTokenURL = HttpConnectionUtil.AccessUrlGet(WECHAT_URL);System.out.println("new accessTokenResult URL :"+accessTokenURL);if(accessTokenURL != null && !accessTokenURL.equals("")){AccessToken accessToken = (AccessToken) JsonUtil.JsonToObject(accessTokenURL, AccessToken.class);if(accessToken != null){access_token = accessToken.getAccess_token();;System.out.println("new_access_token============:"+access_token);}else{System.out.println("accessTokenResult error:"+accessToken);}}}catch(Exception e){System.out.println("getAccessToken Exception:" + e);}return access_token;}}

以下为菜单类

package com.xxx.wechat;import java.util.List;/*** 微信菜单* @author xxxx* @date 11月16日 下午3:22:10* @version V1.0*/public class WechatMenu {/*** 一级菜单数组,个数应为1~3个*/private List<WechatMenu> button;/*** 二级菜单数组,个数应为1~5个*/private List<WechatMenu> sub_button;/*** 菜单的响应动作类型,view表示网页类型,click表示点击类型,miniprogram表示小程序类型*/private String type;/*** 菜单标题,不超过16个字节,子菜单不超过60个字节*/private String name;/*** click等点击类型必须* 菜单KEY值,用于消息接口推送,不超过128字节;*/private String key;/*** view、miniprogram类型必须;* 网页链接,用户点击菜单可打开链接,不超过1024字节。type为miniprogram时,不支持小程序的老版本客户端将打开本url。*/private String url;/*** media_id类型和view_limited类型必须* 调用新增永久素材接口返回的合法media_id*/private String media_id;/*** miniprogram类型必须* 小程序的appid(仅认证公众号可配置)*/private String appid;/*** miniprogram类型必须;* 小程序的页面路径*/private String pagepath;/*** 创建一个新的实例 WechatMenu.*/public WechatMenu() {super();}/*** @return button*/public List<WechatMenu> getButton() {return button;}/*** @param button the button to set*/public void setButton(List<WechatMenu> button) {this.button = button;}/*** @return sub_button*/public List<WechatMenu> getSub_button() {return sub_button;}/*** @param sub_button the sub_button to set*/public void setSub_button(List<WechatMenu> sub_button) {this.sub_button = sub_button;}/*** @return type*/public String getType() {return type;}/*** @param type the type to set*/public void setType(String type) {this.type = type;}/*** @return name*/public String getName() {return name;}/*** @param name the name to set*/public void setName(String name) {this.name = name;}/*** @return key*/public String getKey() {return key;}/*** @param key the key to set*/public void setKey(String key) {this.key = key;}/*** @return url*/public String getUrl() {return url;}/*** @param url the url to set*/public void setUrl(String url) {this.url = url;}/*** @return media_id*/public String getMedia_id() {return media_id;}/*** @param media_id the media_id to set*/public void setMedia_id(String media_id) {this.media_id = media_id;}/*** @return appid*/public String getAppid() {return appid;}/*** @param appid the appid to set*/public void setAppid(String appid) {this.appid = appid;}/*** @return pagepath*/public String getPagepath() {return pagepath;}/*** @param pagepath the pagepath to set*/public void setPagepath(String pagepath) {this.pagepath = pagepath;}}

请求外链接方法

public static String AccessUrl(String url, String postString) {String result = null;HttpURLConnection conn = null;try {URL postUrl = new URL(url);conn = (HttpURLConnection) postUrl.openConnection();conn.setRequestMethod("POST");conn.setDoOutput(true);conn.setDoInput(true);conn.setUseCaches(false);conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");conn.setConnectTimeout(10000);conn.setReadTimeout(10000);OutputStream os = conn.getOutputStream();os.write(postString.getBytes("UTF-8")); // 往远程URL传递参数os.flush();os.close();int code = conn.getResponseCode();conn.getHeaderFields();conn.getContentLength();if (code == 200) {// 返回成功BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));String line;StringBuffer buffer = new StringBuffer();while ((line = reader.readLine()) != null) {buffer.append(line);}result = buffer.toString();} else {logger.error("返回失败:" + code);}} catch (MalformedURLException e) {logger.error("Exception:" + e.getMessage());} catch (IOException e) {logger.error("Exception:" + e.getMessage());}finally{if(conn != null){conn.disconnect();conn=null;}}return result;}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。