最近写了关于微信公众号生成带参数的二维码的一个工具类,直接上代码:
import java.io.IOException; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; import net.sf.json.JSONObject; import org.apache.http.ParseException; import org.apache.log4j.Logger; import com.qicha.model.weixin.AccessToken; /** * * @author pc dell * 创建微信公众号二维码工具类 * */ public class QrCodeUtil { private static Logger logger = Logger.getLogger(QrCodeUtil.class); //创建二维码 private static final String CREATE_QRCODE_URL = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=TOKEN"; private static final String SHOWCODE_PATH = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=TICKET"; /*** * 创建永久二维码Ticket * @param sceneStr 场景值id * @param accessToken 微信全局票据 * @return * @throws ParseException * @throws IOException */ public static String createForeverStrTicket(String sceneStr,String accessToken) throws ParseException, IOException { String ticket=""; TreeMap<String,String> params = new TreeMap<String,String>(); params.put("access_token", accessToken); String url = CREATE_QRCODE_URL.replace("TOKEN", accessToken); Map<String,String> intMap = new HashMap<String,String>(); intMap.put("scene_str",sceneStr); Map<String,Map<String,String>> mapMap = new HashMap<String,Map<String,String>>(); mapMap.put("scene", intMap); Map<String,Object> paramsMap = new HashMap<String,Object>(); paramsMap.put("action_name", "QR_LIMIT_STR_SCENE"); paramsMap.put("action_info", mapMap); String data =JSONObject.fromObject(paramsMap).toString(); logger.info("data:"+data); JSONObject jsonObject = WeixinUtil.doPostStr(url, data); logger.info("jsonObject:"+jsonObject); if(jsonObject!=null){ ticket = jsonObject.optString("ticket"); } return ticket; } /*** * 根据ticket票据,生成二维码图片路径(获取时用get方式) * @param ticket * @return 图片路径 * @throws ParseException * @throws IOException */ public static String showQrCode(String ticket) throws ParseException, IOException { ticket = URLEncoder.encode(ticket, "UTF-8"); String url = SHOWCODE_PATH.replace("TICKET",ticket); return url; } public static void main(String[] args) throws ParseException, IOException { //获取全局票据 String accessToken = ""; String ticked = createForeverStrTicket("10",accessToken); logger.info("永久二维码ticked:"+ticked); String url = showQrCode(ticked); logger.info("永久二维码图片路径:"+url);//直接浏览器访问,下载即可 } }
上边
WeixinUtil.doPostStr方法:
/** * POST请求 * @param url * @param outStr * @return * @throws ParseException * @throws IOException */ public static JSONObject doPostStr(String url,String outStr) throws ParseException, IOException{ HttpClient client = HttpClients.createDefault(); HttpPost httpost = new HttpPost(url); JSONObject jsonObject = null; httpost.setEntity(new StringEntity(outStr,"UTF-8")); HttpResponse response = client.execute(httpost); HttpEntity entity = response.getEntity(); if (entity != null) { String result = EntityUtils.toString(response.getEntity(),"UTF-8"); jsonObject = JSONObject.fromObject(result); } return jsonObject; }