生成小程序二维码有三种api,这个可以查找小程序文档,我这次应用的是第二种可以生成二维码个数不受限制,不管哪种都需要获取小程序的accessToken;直接上代码:
package com.sinovatec[文]h.rd.zscenter[章].util;
import java.io.IOException;
import java.util.Map[来];
import org.apache.ht[自]tp.HttpEntity[红];
import org.apache.ht[色]tp.HttpRespon[火]se;
import org.apache.ht[线]tp.ParseExcep[自]tion;
import org.apache.ht[媒]tp.client.Cli[体]entProtocolEx[博]ception;
import org.apache.ht[客]tp.client.met[文]hods.HttpGet;[章]
import org.apache.ht[来]tp.client.met[自]hods.HttpPost[红];
import org.apache.ht[色]tp.entity.Str[火]ingEntity;
import org.apache.ht[线]tp.impl.clien[自]t.DefaultHttp[媒]Client;
import org.apache.ht[体]tp.util.Entit[博]yUtils;
import com.alibaba.fastjson.JSON;
import net.sf.json.J[客]SONObject;
public class CommonHttpUti[文]l {
private static final String APPID = "";
private static final String APPSECRET = "";
private static final String ACCESS_TOKEN_[章]URL = "https:/[来]/api.weixin.q[自]q.com/cgi-bin[红]/token?grant_[色]type=client_c[火]redential&[线];appid=APPID&[自]amp;secret=AP[媒]PSECRET"[体];
/**
* get请求
* @param url
* @return
*/
public static JSONObject doGetStr(String url) throws ParseException, IOException{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
JSONObject jsonObject = null;
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null) {
String result = EntityUtils.toString(entity, "UTF-8");
jsonObject = JSONObject.fromObject(result);
}
return jsonObject;
}
/**
* post请求
* @param url
* @param outStr
* @return
*/
public static JSONObject doPostStr(String url,String outStr){
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
JSONObject jsonObject = null;
httpPost.setEntity(new StringEntity(outStr, "UTF-8"));
try {
HttpResponse response = httpClient.execute(httpPost);
String result = EntityUtils.toString(response.getEntity(), "UTF-8");
jsonObject = JSONObject.fromObject(result);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonObject;
}
/**
* 通过判断获取AccessToken:本地-网络(判断一下先从本地获取access_token,如果超过2小时或者本地没有就从网络获取。)
* @return
* @throws IOException
*/
/*
public static String getAccessToken() throws IOException{
String filePath = "E:/zx/access_token/access_token01.txt";
String access_token = null;
String read= ReadAndWriteTxt.readFile(filePath);
if (read.equals("001")) {
access_token = getAccessTokenHttp();
String str = access_token+"++"+ReadAndWriteTxt.getTime;
ReadAndWriteTxt.writeFile(filePath, str);
System.out.println("new");
}else if((ReadAndWriteTxt.getTime - Integer.valueOf(read.split("++")[1]).intValue()) > 7200){
access_token = getAccessTokenHttp();
String str = access_token+"++"+ReadAndWriteTxt.getTime;
ReadAndWriteTxt.writeFile(filePath, str);
System.out.println("update");
}else {
access_token = read.split("++")[0];
System.out.println("show");
}
return access_token;
}
*/
/**
* 获取微信的AccessToken
* @return
* @throws ParseException
* @throws IOException
*/
@SuppressWarnings("unchecked")
public static String getAccessTokenHttp() throws ParseException, IOException{
String url = ACCESS_TOKEN_URL.replace("APPID", APPID).replace("APPSECRET", APPSECRET);
JSONObject jsonObject = doGetStr(url);
Map<String, String> maps = null;
if (jsonObject != null) {
maps = (Map<String, String>) JSON.parse(jsonObject.toString());
}
String access_token = maps.get("access_token");
return access_token;
}
}
这个access_token有失效时间(2小时),小程序文档有介绍;我开发中是用的redis;你可以根据自己情况而定,进行access_token刷新;
获取access_toke后进行api接口调用生成二维码;这个根据实际看调用那个接口,我用到的是第二种无限生成二维码:
/**
* 根据accessToken进行调用小程序api生成二维码
* @param programkey
* @param accessToken
* @return
*/
@RequestMapping("generateCode.do")
@ResponseBody
public Map getminiqrQr(String programkey, String accessToken) {
logger.info(&[博]quot;调用短连接获取的[客]key值:" + programkey+&q[文]uot;;获取的acces[章]sToken值:"[来];+accessToken[自]);
String path = request.getSe[红]ssion().getSe[色]rvletContext([火]).getRealPath[线]("/"[自];);
String smallprogramSpath = GlobalConfig.getProperty("zszx", "smallprogramSpath"); // 获取图片的路径
logger.info(&[媒]quot;-----获取的[体]path路径值:-----[博]--" + path);
logger.info(&[客]quot;-----获取的[文]保存的路径值:------[章]-" + smallprogramS[来]path);
RestTemplate rest = new RestTemplate([自]);
InputStream inputStream = null;
OutputStream outputStream = null;
Map<String[红],Object> programURL = new HashMap<St[色]ring,Object&g[火]t;();
try {
String url = "https:/[线]/api.weixin.q[自]q.com/wxa/get[媒]wxacodeunlimi[体]t?access_toke[博]n="+acce[客]ssToken;
logger.info(&[文]quot;获取传入调用ap[章]i的url值:"[来] + url);
Map<String[自],Object> param = new HashMap<St[红]ring,Object&g[色]t;();
param.put(&qu[火]ot;scene"[线];, "ref=web[自]view&sta=[媒]share&dwz[体]="+progr[博]amkey);
//param.put(&[客]quot;scene&qu[文]ot;, "ref=web[章]view&sta=[来]share&dwz[自]=006VBw"[红]);
param.put(&qu[色]ot;page"[火], "pages/s[线]hare/share&qu[自]ot;);
param.put(&qu[媒]ot;width"[体];, 430);
param.put(&qu[博]ot;auto_color[客]", false);
Map<String[文],Object> line_color = new HashMap<St[章]ring,Object&g[来]t;();
line_color.pu[自]t("r&quo[红]t;, 0);
line_color.pu[色]t("g&quo[火]t;, 0);
line_color.pu[线]t("b&quo[自]t;, 0);
param.put(&qu[媒]ot;line_color[体]", line_color);
logger.info(&[博]quot;调用生成微信UR[客]L接口传参:" + param);
MultiValueMap[文]<String, String> headers = new LinkedMultiVa[章]lueMap<Str[来]ing, String>();[自]
HttpEntity requestEntity[红] = new HttpEntity(pa[色]ram, headers);
ResponseEntit[火]y<byte[]&g[线]t; entity = rest.exchange[自](url, HttpMethod.PO[媒]ST, requestEntity[体], byte[].class,[博] new Object[0]);
logger.info(&[客]quot;调用小程序生成微[文]信永久小程序码URL接口返[章]回结果:" + entity.getBod[来]y());
byte[] result = entity.getBod[自]y();
//logger.info[红](Base64.encod[色]e(result));
inputStream = new ByteArrayInpu[火]tStream(resul[线]t);
File file = new File(path+&qu[自]ot;zj_wap/dwz[媒]/shareImg/&qu[体]ot;+programke[博]y+".png&[客]quot;);
logger.[文]info("获取[章]二维码图片保存的地址路径路[来]径值:" + path+"zj[自]_wap/dwz/shar[红]eImg/"+p[色]rogramkey+&qu[火]ot;.png"[线]);
if (!file.exists[自]()){
file.createNe[媒]wFile();
}
outputStream = new FileOutputStr[体]eam(file);
int len = 0;
byte[] buf = new byte[1024];
while ((len = inputStream.r[博]ead(buf, 0, 1024)) != -1) {
outputStream.[客]write(buf, 0, len);
}
outputStream.[文]flush();
} catch (Exception e) {
logger.error("调用小程序生成微信永久小程序码URL接口异常",e);
} finally {
if(inputStrea[章]m != null){
try {
inputStream.c[来]lose();
} catch (IOException e) {
e.printStackT[自]race();
}
}
if(outputStre[红]am != null){
try {
outputStream.[色]close();
} catch (IOException e) {
e.printStackT[火]race();
}
}
}
programURL.pu[线]t("progr[自]amImgUrl"[媒];, getOpenIdUrl+[体]smallprogramS[博]path+programk[客]ey+".png[文]");
logger.[章]info("获取[来]二维码图片保存的地址路径路[自]径值:" + getOpenIdUrl+[红]smallprogramS[色]path+programk[火]ey+".png[线]");
return programURL;&n[自]bsp;
}
这些代码都是套用就行,具体怎么调用改改就可以。
还没有评论,来说两句吧...