微信公众号自定义菜单Java生成

由于近段时间在搞微信公众号,需要java生成方便讨论自定义菜单,现将源码分享给大家

ClickButton.java

public class ClickButton {
	private String type;
	private String name;
	private String key;

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getKey() {
		return key;
	}

	public void setKey(String key) {
		this.key = key;
	}

}

GetAccessTokenRsp.java

import java.io.Serializable;

public class GetAccessTokenRsp implements Serializable {

	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = -7021131613095678023L;

	private String accessToken;

	public String getAccessToken() {
		return accessToken;
	}

	public void setAccessToken(String accessToken) {
		this.accessToken = accessToken;
	}

	@Override
	public String toString() {
		return "GetAccessTokenRsp [accessToken=" + accessToken + "]";
	}

}
HttpUtils.java
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.zip.GZIPInputStream;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

/**
 * ClassName: HttpUtils
 * 
 * @Description: http请求工具类
 * @author dapengniao
 * @date 2016年3月10日 下午3:57:14
 */
@SuppressWarnings("deprecation")
public class HttpUtils {

	/**
	 * @Description: http get请求共用方法
	 * @param @param reqUrl
	 * @param @param params
	 * @param @return
	 * @param @throws Exception
	 * @author dapengniao
	 * @date 2016年3月10日 下午3:57:39
	 */
	@SuppressWarnings("resource")
	public static String sendGet(String reqUrl, Map params)
			throws Exception {
		InputStream inputStream = null;
		HttpGet request = new HttpGet();
		try {
			String url = buildUrl(reqUrl, params);
			HttpClient client = new DefaultHttpClient();

			request.setHeader("Accept-Encoding", "gzip");
			request.setURI(new URI(url));

			HttpResponse response = client.execute(request);

			inputStream = response.getEntity().getContent();
			String result = getJsonStringFromGZIP(inputStream);
			return result;
		} finally {
			if (inputStream != null) {
				inputStream.close();
			}
			request.releaseConnection();
		}

	}

	/**
	 * @Description: http post请求共用方法
	 * @param @param reqUrl
	 * @param @param params
	 * @param @return
	 * @param @throws Exception
	 * @author dapengniao
	 * @date 2016年3月10日 下午3:57:53
	 */
	@SuppressWarnings("resource")
	public static String sendPost(String reqUrl, Map params)
			throws Exception {
		try {
			Set set = params.keySet();
			List list = new ArrayList();
			for (String key : set) {
				list.add(new BasicNameValuePair(key, params.get(key)));
			}
			if (list.size() > 0) {
				try {
					HttpClient client = new DefaultHttpClient();
					HttpPost request = new HttpPost(reqUrl);

					request.setHeader("Accept-Encoding", "gzip");
					request.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8));

					HttpResponse response = client.execute(request);

					InputStream inputStream = response.getEntity().getContent();
					try {
						String result = getJsonStringFromGZIP(inputStream);

						return result;
					} finally {
						inputStream.close();
					}
				} catch (Exception ex) {
					ex.printStackTrace();
					throw new Exception("网络连接失败,请连接网络后再试");
				}
			} else {
				throw new Exception("参数不全,请稍后重试");
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			throw new Exception("发送未知异常");
		}
	}

	/**
	 * @Description: http post请求json数据
	 * @param @param urls
	 * @param @param params
	 * @param @return
	 * @param @throws ClientProtocolException
	 * @param @throws IOException
	 * @author dapengniao
	 * @date 2016年3月10日 下午3:58:15
	 */
	public static String sendPostBuffer(String urls, String params)
			throws ClientProtocolException, IOException {
		HttpPost request = new HttpPost(urls);

		StringEntity se = new StringEntity(params, HTTP.UTF_8);
		request.setEntity(se);
		// 发送请求
		@SuppressWarnings("resource")
		HttpResponse httpResponse = new DefaultHttpClient().execute(request);
		// 得到应答的字符串,这也是一个 JSON 格式保存的数据
		String retSrc = EntityUtils.toString(httpResponse.getEntity());
		request.releaseConnection();
		return retSrc;

	}

	/**
	 * @Description: http请求发送xml内容
	 * @param @param urlStr
	 * @param @param xmlInfo
	 * @param @return
	 * @author dapengniao
	 * @date 2016年3月10日 下午3:58:32
	 */
	public static String sendXmlPost(String urlStr, String xmlInfo) {
		// xmlInfo xml具体字符串

		try {
			URL url = new URL(urlStr);
			URLConnection con = url.openConnection();
			con.setDoOutput(true);
			con.setRequestProperty("Pragma:", "no-cache");
			con.setRequestProperty("Cache-Control", "no-cache");
			con.setRequestProperty("Content-Type", "text/xml");
			OutputStreamWriter out = new OutputStreamWriter(
					con.getOutputStream());
			out.write(new String(xmlInfo.getBytes("utf-8")));
			out.flush();
			out.close();
			BufferedReader br = new BufferedReader(new InputStreamReader(
					con.getInputStream()));
			String lines = "";
			for (String line = br.readLine(); line != null; line = br
					.readLine()) {
				lines = lines + line;
			}
			return lines; // 返回请求结果
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "fail";
	}

	private static String getJsonStringFromGZIP(InputStream is) {
		String jsonString = null;
		try {
			BufferedInputStream bis = new BufferedInputStream(is);
			bis.mark(2);
			// 取前两个字节
			byte[] header = new byte[2];
			int result = bis.read(header);
			// reset输入流到开始位置
			bis.reset();
			// 判断是否是GZIP格式
			int headerData = getShort(header);
			// Gzip 流 的前两个字节是 0x1f8b
			if (result != -1 && headerData == 0x1f8b) {
				// LogUtil.i("HttpTask", " use GZIPInputStream  ");
				is = new GZIPInputStream(bis);
			} else {
				// LogUtil.d("HttpTask", " not use GZIPInputStream");
				is = bis;
			}
			InputStreamReader reader = new InputStreamReader(is, "utf-8");
			char[] data = new char[100];
			int readSize;
			StringBuffer sb = new StringBuffer();
			while ((readSize = reader.read(data)) > 0) {
				sb.append(data, 0, readSize);
			}
			jsonString = sb.toString();
			bis.close();
			reader.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return jsonString;
	}

	private static int getShort(byte[] data) {
		return (data[0] << 8) | data[1] & 0xFF;
	}

	/**
	 * 构建get方式的url
	 * 
	 * @param reqUrl
	 *            基础的url地址
	 * @param params
	 *            查询参数
	 * @return 构建好的url
	 */
	public static String buildUrl(String reqUrl, Map params) {
		StringBuilder query = new StringBuilder();
		Set set = params.keySet();
		for (String key : set) {
			query.append(String.format("%s=%s&", key, params.get(key)));
		}
		return reqUrl + "?" + query.toString();
	}
}

Token.java
import java.io.IOException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.log4j.Logger;
import org.springframework.util.StringUtils;

public class Token {

	private static final Logger DEBUG_LOGGER = Logger.getLogger(Token.class);

	/**
	 * 
	 * 获取微信access_token <功能详细描述>
	 * 
	 * @param appid
	 * @param secret
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	public static GetAccessTokenRsp getWeiXinAccessToken(String appid,
			String secret) {
		if (StringUtils.isEmpty(appid) || StringUtils.isEmpty(secret)) {
			DEBUG_LOGGER.error("appid or secret is null");
			return null;
		}
		GetAccessTokenRsp getAccessTokenRsp = new GetAccessTokenRsp();
		try {
			String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
					+ appid + "&secret=" + secret;
			HttpClient httpClient = new HttpClient();
			GetMethod getMethod = new GetMethod(url);
			int execute = httpClient.executeMethod(getMethod);
			System.out.println("execute:" + execute);
			String getResponse = getMethod.getResponseBodyAsString();
			getAccessTokenRsp.setAccessToken(getResponse);
		} catch (IOException e) {
			DEBUG_LOGGER.error("getAccessToken failed,desc:::" + e);
			e.printStackTrace();
		}
		System.out.println(getAccessTokenRsp);
		return getAccessTokenRsp;
	}

}
ViewButton.java
public class ViewButton {
	private String type;
	private String name;
	private String url;

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

}
MenuMain.java
import com.alibaba.fastjson.JSONObject;
 
import net.sf.json.JSONArray;
 
public class MenuMain {
	public static String APP_ID = "wx94b9f9848e25f2e5";
	public static String SECRET = "1c94653d0a6fa9df77b549017045acf4";
    public static void main(String[] args) {
    	
     
        ClickButton cbt=new ClickButton();
        cbt.setKey("image");
        cbt.setName("回复图片");
        cbt.setType("click");
         
         
        ViewButton vbt=new ViewButton();
        vbt.setUrl("http://www.ylcloudcastle.cn/ytw/index.html");
        vbt.setName("云屯网");
        vbt.setType("view");
        
        ViewButton vbt1=new ViewButton();
        vbt1.setUrl("http://www.ylcloudcastle.cn/ytw/ytw/excellentstorelist_body.html");
        vbt1.setName("入驻企业");
        vbt1.setType("view");
        
        ViewButton vbt2=new ViewButton();
        vbt2.setUrl("http://www.ylcloudcastle.cn/ytw/ytw/contactUs.html");
        vbt2.setName("关于我们");
        vbt2.setType("view");
        
         
        JSONArray sub_button=new JSONArray();
        sub_button.add(vbt2);
         
         
        JSONObject buttonOne=new JSONObject();
        buttonOne.put("name", "关于我们");
        buttonOne.put("sub_button", sub_button);
         
        JSONArray button=new JSONArray();
        button.add(vbt);
        button.add(vbt1);
        button.add(vbt2);
//        button.add(buttonOne);
//        button.add(cbt);
         
        JSONObject menujson=new JSONObject();
        menujson.put("button", button);
        System.out.println(menujson);
        GetAccessTokenRsp token = Token.getWeiXinAccessToken(APP_ID, SECRET);
        System.out.println(token.getAccessToken());
        //这里为请求接口的url   +号后面的是token,这里就不做过多对token获取的方法解释
        String url="https://api.weixin.qq.com/cgi-bin/menu/create?access_token="+token.getAccessToken();
//        System.out.println(url);
         
        try{
            String rs=HttpUtils.sendPostBuffer(url, menujson.toJSONString());
            System.out.println("成功");
            System.out.println(rs);
        }catch(Exception e){
            System.out.println("请求错误!");
        }
     
    }
 
}

生成后

微信公众号自定义菜单Java生成_第1张图片


参考了这边文章:点击打开链接


你可能感兴趣的:(java)