Springboot读取静态json文件(微信公众号自定义菜单和删除全部菜单)

一,目录结构

2.pom引入

  <!-- io操作的工具类库 -->
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.3</version>
		</dependency>

  

package com.grand.weichat;

import java.io.IOException;
import java.nio.charset.Charset;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.Resource;
import org.springframework.test.context.junit4.SpringRunner;
import com.grand.weichat.util.base.WXUtilsCenter;
import cn.hutool.http.HttpUtil;
import net.sf.json.JSONObject;

@RunWith(SpringRunner.class)
@SpringBootTest
public class Menu {

	@Value("${conf.appId}")
	private  String appId;

	@Value("${conf.appSecret}")
	private  String appSecret;

	@Value("classpath:static/menu.json")
	private Resource menujson;

	/**
	 * 删除所有自定义菜单
	 */
	@Test
	public void deleteAllMenu() {
		String token=WXUtilsCenter.getAccessToken(appId,appSecret);
		String url="https://api.weixin.qq.com/cgi-bin/menu/delete?access_token="+token;
		String result = HttpUtil.get(url);
		JSONObject json=JSONObject.fromObject(result);
		if((Integer)json.get("errcode") == 0){
			System.out.println("删除菜单成功");
		}else{
			System.out.println("删除菜单失败");
		}
	}
	//自定义菜单生成
	@Test
	public void testMenu(){
		try {
			//1.系统目录下拿到自定义菜单的json数据
			String areaData = IOUtils.toString(menujson.getInputStream(), Charset.forName("UTF-8"));
			System.out.println(areaData);

			//2.拿到access_token发起请求生成自定义菜单
			String token=WXUtilsCenter.getAccessToken(appId,appSecret);
			String url="https://api.weixin.qq.com/cgi-bin/menu/create?access_token="+token+"";
			String result = HttpUtil.post(url, areaData.toString());
			JSONObject json=JSONObject.fromObject(result);
			if((Integer)json.get("errcode") == 0){
				System.out.println("设置菜单成功");
			}else{
				System.out.println("设置菜单失败");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

  

猜你喜欢

转载自www.cnblogs.com/KdeS/p/12600165.html