生成小程序二维码有三种api,这个可以查找小程序文档,我这次应用的是第二种可以生成二维码个数不受限制,不管哪种都需要获取小程序的accessToken;直接上代码:
package com.sinovatech.rd.zscenter.util;
import java.io.IOException;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
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.util.EntityUtils;
import com.alibaba.fastjson.JSON;
import net.sf.json.JSONObject;
public class CommonHttpUtil {
private static final String APPID = "";
private static final String APPSECRET = "";
private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
/**
* 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("调用短连接获取的key值:" + programkey+";获取的accessToken值:"+accessToken);
String path = request.getSession().getServletContext().getRealPath("/");
String smallprogramSpath = GlobalConfig.getProperty("zszx", "smallprogramSpath"); // 获取图片的路径
logger.info("-----获取的path路径值:-------" + path);
logger.info("-----获取的保存的路径值:-------" + smallprogramSpath);
RestTemplate rest = new RestTemplate();
InputStream inputStream = null;
OutputStream outputStream = null;
Map<String,Object> programURL = new HashMap<String,Object>();
try {
String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+accessToken;
logger.info("获取传入调用api的url值:" + url);
Map<String,Object> param = new HashMap<String,Object>();
param.put("scene", "ref=webview&sta=share&dwz="+programkey);
//param.put("scene", "ref=webview&sta=share&dwz=006VBw");
param.put("page", "pages/share/share");
param.put("width", 430);
param.put("auto_color", false);
Map<String,Object> line_color = new HashMap<String,Object>();
line_color.put("r", 0);
line_color.put("g", 0);
line_color.put("b", 0);
param.put("line_color", line_color);
logger.info("调用生成微信URL接口传参:" + param);
MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
HttpEntity requestEntity = new HttpEntity(param, headers);
ResponseEntity<byte[]> entity = rest.exchange(url, HttpMethod.POST, requestEntity, byte[].class, new Object[0]);
logger.info("调用小程序生成微信永久小程序码URL接口返回结果:" + entity.getBody());
byte[] result = entity.getBody();
//logger.info(Base64.encode(result));
inputStream = new ByteArrayInputStream(result);
File file = new File(path+"zj_wap/dwz/shareImg/"+programkey+".png");
logger.info("获取二维码图片保存的地址路径路径值:" + path+"zj_wap/dwz/shareImg/"+programkey+".png");
if (!file.exists()){
file.createNewFile();
}
outputStream = new FileOutputStream(file);
int len = 0;
byte[] buf = new byte[1024];
while ((len = inputStream.read(buf, 0, 1024)) != -1) {
outputStream.write(buf, 0, len);
}
outputStream.flush();
} catch (Exception e) {
logger.error("调用小程序生成微信永久小程序码URL接口异常",e);
} finally {
if(inputStream != null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(outputStream != null){
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
programURL.put("programImgUrl", getOpenIdUrl+smallprogramSpath+programkey+".png");
logger.info("获取二维码图片保存的地址路径路径值:" + getOpenIdUrl+smallprogramSpath+programkey+".png");
return programURL;
}
这些代码都是套用就行,具体怎么调用改改就可以。
还没有评论,来说两句吧...