微信公众号java开发:生成底部菜单(上传素材)

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

import com.alibaba.fastjson.JSONObject;
import com.cetcnav.operations.util.WeixinUtil;

public class Main {

	public static void main(String[] args) {

		try {
			// 获取access_token
			// 测试的
			String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx30d92d5c1507e2c6&secret=9fbaee41a1e2db00214321e28b9fda68";
			// 正式环境的
			// String url =
			// "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx78921b3d567f497d&secret=c73e1b9a7b851a7cc5c3bace12de7997";
			JSONObject data = WeixinUtil.httpRequest(url, "GET", null);
			String token = data.getString("access_token");

			// 上传永久图片素材
			/*
			 * //图片地址 String path =
			 * "C:/Users/dell/Pictures/微信图片_20201016151838.png"; JSONObject
			 * object = addMaterialEver(path,"image",token);
			 * System.out.println(object.toString()); String media_id =
			 * object.getString("media_id");
			 */

			// 查看永久素材
			/*
			 * String batchget_material =
			 * "https://api.weixin.qq..com/cgi-bin/material/batchget_material?access_token="
			 * +token; JSONObject JSONObject =
			 * WeixinUtil.httpRequest(batchget_material, "POST",
			 * "{\"type\":\"image\",\"offset\":0,\"count\":20}");
			 * System.out.println(JSONObject);
			 */

			// 生成菜单
			String createurl = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + token;
			// 本地
			// String json =
			// "{\"button\":[{\"name\":\"我的\",\"sub_button\":[{\"type\":\"view\",\"name\":\"智慧接待\",\"url\":\"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx30d92d5c1507e2c6&redirect_uri=http%3A%2F%2F222.222.216.214%3A9900%2Fcetcnav_instrument_operations%2Frest%2Fhome%2FsmartReceptionHome&response_type=code&scope=snsapi_userinfo&state=123&connect_redirect=1#wechat_redirect\"}]}]}";
			String json = "{\"button\":[{\"name\":\"我的\",\"sub_button\":[{\"type\":\"view\",\"name\":\"智慧接待\",\"url\":\"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx30d92d5c1507e2c6&redirect_uri=http%3A%2F%2F222.222.216.214%3A9900%2Fcetcnav_instrument_operations%2Frest%2Fhome%2FsmartReceptionHome&response_type=code&scope=snsapi_userinfo&state=123&connect_redirect=1#wechat_redirect\"}]}]}";
			// 线上
			// String json =
			// "{\"button\":[{\"type\":\"miniprogram\",\"name\":\"小精灵\",\"url\":\"https://yqgzh.cetnav.com/default\",\"appid\":\"wx72ddcf45172520e0\",\"pagepath\":\"pages/login/login\"},{\"type\":\"media_id\",\"name\":\"使用手册\",\"media_id\":\"e1UnFFNMIOkQpy52_pTaX_N6OG5RuMVwP_v0vpoOArc\"},{\"name\":\"我的\",\"sub_button\":[{\"type\":\"view\",\"name\":\"积分兑换\",\"url\":\"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx78921b3d567f497d&redirect_uri=https%3A%2F%2Fyqgzh.cetnav.com%2Fcetcnav_instrument_operations%2Frest%2Fhome%2FscoreConvertHome&response_type=code&scope=snsapi_userinfo&state=123&connect_redirect=1#wechat_redirect\"},{\"type\":\"view\",\"name\":\"个人信息\",\"url\":\"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx78921b3d567f497d&redirect_uri=https%3A%2F%2Fyqgzh.cetnav.com%2Fcetcnav_instrument_operations%2Frest%2Fhome%2FuserInfoHome&response_type=code&scope=snsapi_userinfo&state=123&connect_redirect=1#wechat_redirect\"},{\"type\":\"view\",\"name\":\"我要留言\",\"url\":\"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx78921b3d567f497d&redirect_uri=https%3A%2F%2Fyqgzh.cetnav.com%2Fcetcnav_instrument_operations%2Frest%2Fhome%2FuserSuggestHome&response_type=code&scope=snsapi_userinfo&state=123&connect_redirect=1#wechat_redirect\"}]}]}";
			// 测试线上增加智慧接待的
			// String json =
			// "{\"button\":[{\"type\":\"miniprogram\",\"name\":\"小精灵\",\"url\":\"https://yqgzh.cetnav.com/default\",\"appid\":\"wx72ddcf45172520e0\",\"pagepath\":\"pages/login/login\"},{\"type\":\"media_id\",\"name\":\"使用手册\",\"media_id\":\"e1UnFFNMIOkQpy52_pTaX_N6OG5RuMVwP_v0vpoOArc\"},{\"name\":\"我的\",\"sub_button\":[{\"type\":\"view\",\"name\":\"积分兑换\",\"url\":\"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx78921b3d567f497d&redirect_uri=https%3A%2F%2Fyqgzh.cetnav.com%2Fcetcnav_instrument_operations%2Frest%2Fhome%2FscoreConvertHome&response_type=code&scope=snsapi_userinfo&state=123&connect_redirect=1#wechat_redirect\"},{\"type\":\"view\",\"name\":\"个人信息\",\"url\":\"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx78921b3d567f497d&redirect_uri=https%3A%2F%2Fyqgzh.cetnav.com%2Fcetcnav_instrument_operations%2Frest%2Fhome%2FuserInfoHome&response_type=code&scope=snsapi_userinfo&state=123&connect_redirect=1#wechat_redirect\"},{\"type\":\"view\",\"name\":\"我要留言\",\"url\":\"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx78921b3d567f497d&redirect_uri=https%3A%2F%2Fyqgzh.cetnav.com%2Fcetcnav_instrument_operations%2Frest%2Fhome%2FuserSuggestHome&response_type=code&scope=snsapi_userinfo&state=123&connect_redirect=1#wechat_redirect\"},{\"type\":\"view\",\"name\":\"智慧接待\",\"url\":\"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx78921b3d567f497d&redirect_uri=https%3A%2F%2Fyqgzh.cetnav.com%2Fcetcnav_instrument_operations%2Frest%2Fhome%2FsmartReceptionHome&response_type=code&scope=snsapi_userinfo&state=123&connect_redirect=1#wechat_redirect\"},{\"name\":\"我的\",\"sub_button\":[{\"type\":\"view\",\"name\":\"积分兑换\",\"url\":\"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx78921b3d567f497d&redirect_uri=https%3A%2F%2Fyqgzh.cetnav.com%2Fcetcnav_instrument_operations%2Frest%2Fhome%2FscoreConvertHome&response_type=code&scope=snsapi_userinfo&state=123&connect_redirect=1#wechat_redirect\"},{\"type\":\"view\",\"name\":\"个人信息\",\"url\":\"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx78921b3d567f497d&redirect_uri=https%3A%2F%2Fyqgzh.cetnav.com%2Fcetcnav_instrument_operations%2Frest%2Fhome%2FuserInfoHome&response_type=code&scope=snsapi_userinfo&state=123&connect_redirect=1#wechat_redirect\"},{\"type\":\"view\",\"name\":\"我要留言\",\"url\":\"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx78921b3d567f497d&redirect_uri=https%3A%2F%2Fyqgzh.cetnav.com%2Fcetcnav_instrument_operations%2Frest%2Fhome%2FuserSuggestHome&response_type=code&scope=snsapi_userinfo&state=123&connect_redirect=1#wechat_redirect\"}]}]}";
			JSONObject JSONObject = WeixinUtil.httpRequest(createurl, "POST", json);
			System.out.println(JSONObject.toString());

			// 查询
			String URL = "https://api.weixin.qq.com/cgi-bin/get_current_selfmenu_info?access_token=" + token;
			JSONObject josn = WeixinUtil.httpRequest(URL, "GET", null);
			System.out.println(josn);

		} catch (Exception e) {
			System.out.println("---");
		}

	}

	/**
	 * 上传其他永久素材(图片素材的上限为5000,其他类型为1000)
	 *
	 * @return
	 * @throws Exception
	 */
	public static JSONObject addMaterialEver(String fileurl, String type, String token) {
		try {
			File file = new File(fileurl);
			// 上传素材
			String path = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=" + token + "&type="
					+ type;
			String result = connectHttpsByPost(path, null, file);
			result = result.replaceAll("[\\\\]", "");
			System.out.println("result:" + result);
			JSONObject resultJSON = JSONObject.parseObject(result);
			if (resultJSON != null) {
				if (resultJSON.get("media_id") != null) {
					System.out.println("上传" + type + "永久素材成功");
					return resultJSON;
				} else {
					System.out.println("上传" + type + "永久素材失败");
				}
			}
			return null;
		} catch (IOException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchProviderException e) {
			e.printStackTrace();
		} catch (KeyManagementException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String connectHttpsByPost(String path, String KK, File file)
			throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
		URL urlObj = new URL(path);
		// 连接
		HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
		String result = null;
		con.setDoInput(true);

		con.setDoOutput(true);

		con.setUseCaches(false); // post方式不能使用缓存

		// 设置请求头信息
		con.setRequestProperty("Connection", "Keep-Alive");
		con.setRequestProperty("Charset", "UTF-8");
		// 设置边界
		String BOUNDARY = "----------" + System.currentTimeMillis();
		con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

		// 请求正文信息
		// 第一部分:
		StringBuilder sb = new StringBuilder();
		sb.append("--"); // 必须多两道线
		sb.append(BOUNDARY);
		sb.append("\r\n");
		sb.append("Content-Disposition: form-data;name=\"media\";filelength=\"" + file.length() + "\";filename=\""

				+ file.getName() + "\"\r\n");
		sb.append("Content-Type:application/octet-stream\r\n\r\n");
		byte[] head = sb.toString().getBytes("utf-8");
		// 获得输出流
		OutputStream out = new DataOutputStream(con.getOutputStream());
		// 输出表头
		out.write(head);

		// 文件正文部分
		// 把文件已流文件的方式 推入到url中
		DataInputStream in = new DataInputStream(new FileInputStream(file));
		int bytes = 0;
		byte[] bufferOut = new byte[1024];
		while ((bytes = in.read(bufferOut)) != -1) {
			out.write(bufferOut, 0, bytes);
		}
		in.close();
		// 结尾部分
		byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线
		out.write(foot);
		out.flush();
		out.close();
		StringBuffer buffer = new StringBuffer();
		BufferedReader reader = null;
		try {
			// 定义BufferedReader输入流来读取URL的响应
			reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
			String line = null;
			while ((line = reader.readLine()) != null) {
				buffer.append(line);
			}
			if (result == null) {
				result = buffer.toString();
			}
		} catch (IOException e) {
			System.out.println("发送POST请求出现异常!" + e);
			e.printStackTrace();
		} finally {
			if (reader != null) {
				reader.close();
			}
		}
		return result;
	}

}
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;

import com.alibaba.fastjson.JSONObject;
import com.cetcnav.operations.weixin.entity.Image;
import com.cetcnav.operations.weixin.entity.ImageMessage;
import com.cetcnav.operations.weixin.entity.TextMessage;
import com.google.inject.spi.Element;
import com.sun.xml.txw2.Document;
import com.thoughtworks.xstream.XStream;

public class WeixinUtils {

	/**
	 * 文本转换为xml
	 * @MethodName:textMessageToXml
	 *@author:maliran
	 *@ReturnType:String
	 *@param textMessage
	 *@return
	 */
	public static String textMessageToXml(TextMessage textMessage){
		
		XStream xstream = new XStream();//xstream.jar,xmlpull.jar
		xstream.alias("xml", textMessage.getClass());//置换根节点
		System.out.println(xstream.toXML(textMessage));
		return xstream.toXML(textMessage);
		
	}
	/**
	 * 图片转成xml
	 * @MethodName:textMessageToXml
	 *@author:maliran
	 *@ReturnType:String
	 *@param textMessage
	 *@return
	 */
    public static String imageMessageToXml(ImageMessage imageMessage){
		
		XStream xstream = new XStream();//xstream.jar,xmlpull.jar
		xstream.alias("xml", imageMessage.getClass());//置换根节点
		//System.out.println(xstream.toXML(imageMessage));
		return xstream.toXML(imageMessage);
		
	}
	/**
     * 组装图片xml
     * @MethodName:initImageMessage
     *@author:maliran
     *@ReturnType:String
     *@param MediaId
     *@param toUserName
     *@param fromUserName
     *@return
     */
	public static String initImageMessage(String MediaId,String toUserName,String fromUserName){		
		String message = null;
		Image image = new Image();
		ImageMessage imageMessage = new ImageMessage();
		image.setMediaId(MediaId);
		imageMessage.setFromUserName(toUserName);
		imageMessage.setToUserName(fromUserName);
		imageMessage.setCreateTime(new Date().toString());
		imageMessage.setImage(image);
		imageMessage.setMsgType("image");
		message = imageMessageToXml(imageMessage);
		return message;
	}
	public static String initTextMessage(String content,String toUserName,String fromUserName){		
		String message = null;
		TextMessage textMessage = new TextMessage();
		textMessage.setFromUserName(toUserName);
		textMessage.setToUserName(fromUserName);
		textMessage.setCreateTime(new Date().toString());
		textMessage.setContent(content);
		textMessage.setMsgType("text");
		message = textMessageToXml(textMessage);
		return message;
	}
	
	/**
	 * 上传本地文件到微信获取mediaId
	 */
	public static String upload(String filePath, String accessToken,String type) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
		File file = new File(filePath);
		if (!file.exists() || !file.isFile()) {
			throw new IOException("文件不存在");
		}
 
		String url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";
	    url = url.replace("ACCESS_TOKEN", accessToken).replace("TYPE",type);
		
		URL urlObj = new URL(url);
		//连接
		HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
 
		con.setRequestMethod("POST"); 
		con.setDoInput(true);
		con.setDoOutput(true);
		con.setUseCaches(false); 
 
		//设置请求头信息
		con.setRequestProperty("Connection", "Keep-Alive");
		con.setRequestProperty("Charset", "UTF-8");
 
		//设置边界
		String BOUNDARY = "----------" + System.currentTimeMillis();
		con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
 
		StringBuilder sb = new StringBuilder();
		sb.append("--");
		sb.append(BOUNDARY);
		sb.append("\r\n");
		sb.append("Content-Disposition: form-data;name=\"file\";filename=\"" + file.getName() + "\"\r\n");
		sb.append("Content-Type:application/octet-stream\r\n\r\n");
 
		byte[] head = sb.toString().getBytes("utf-8");
 
		//获得输出流
		OutputStream out = new DataOutputStream(con.getOutputStream());
		//输出表头
		out.write(head);
 
		//文件正文部分
		//把文件已流文件的方式 推入到url中
		DataInputStream in = new DataInputStream(new FileInputStream(file));
		int bytes = 0;
		byte[] bufferOut = new byte[1024];
		while ((bytes = in.read(bufferOut)) != -1) {
			out.write(bufferOut, 0, bytes);
		}
		in.close();
 
		//结尾部分
		byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");//定义最后数据分隔线
 
		out.write(foot);
 
		out.flush();
		out.close();
 
		StringBuffer buffer = new StringBuffer();
		BufferedReader reader = null;
		String result = null;
		try {
			//定义BufferedReader输入流来读取URL的响应
			reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
			String line = null;
			while ((line = reader.readLine()) != null) {
				buffer.append(line);
			}
			if (result == null) {
				result = buffer.toString();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				reader.close();
			}
		}
 		JSONObject jsonObj = JSONObject.parseObject(result);
		System.out.println(jsonObj);
		String typeName = "media_id";
		if(!"image".equals(type)){
			typeName = type + "_media_id";
		}
		String mediaId = jsonObj.getString(typeName);
		return mediaId;
	}
}
<dependency>
			<groupId>org.dom4j</groupId>
			<artifactId>dom4j</artifactId>
			<version>2.1.3</version>
		</dependency>
public class Image {

	private String MediaId;

	public String getMediaId() {
		return MediaId;
	}

	public void setMediaId(String mediaId) {
		MediaId = mediaId;
	}
	
}

public class ImageMessage extends Message{

	private Image image;

	public Image getImage() {
		return image;
	}

	public void setImage(Image image) {
		this.image = image;
	}
	
}

public class Message {

	private String ToUserName;
	private String FromUserName;
	private String CreateTime;
	private String MsgType;
	public String getToUserName() {
		return ToUserName;
	}
	public void setToUserName(String toUserName) {
		ToUserName = toUserName;
	}
	public String getFromUserName() {
		return FromUserName;
	}
	public void setFromUserName(String fromUserName) {
		FromUserName = fromUserName;
	}
	public String getCreateTime() {
		return CreateTime;
	}
	public void setCreateTime(String createTime) {
		CreateTime = createTime;
	}
	public String getMsgType() {
		return MsgType;
	}
	public void setMsgType(String msgType) {
		MsgType = msgType;
	}
	
	
}

public class TextMessage extends Message{

	private String Content;

	public String getContent() {
		return Content;
	}

	public void setContent(String content) {
		Content = content;
	}
	
	
}
  • 9
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值