我才用的是https调用方式。这种生成小程序码的方式是生成数量无限制,长期有限,只是参数需要通过scene进行传递。如果数量不多可以直接使用另外一种方式,可以直接在路径中添加参数。
1、首先获取调用api的令牌,accessToken。代码如下
public static String requestWxToken(){
String url = Global.getConfig("accessToken");//获取accessToken的地址
//处理地址
url = url.replace("APPID",Global.getConfig("appid")).replace("APPSECRET",Global.getConfig("appsecret"));
//HttpClientUtil是我自己写的一个工具类,可以随便用能发送get请求即可
String resultStr = HttpClientUtil.doGet(url);
//转换获取的数据
AccessTokenVO accessTokenVO = JSONObject.parseObject(resultStr,AccessTokenVO.class);
if(StringUtils.isBlank(accessTokenVO.getErrcode())||"0".equals(accessTokenVO.getErrcode())){
return accessTokenVO.getAccessToken();
}else{
return null;
}
}
2、构建post请求去请求地址获取文件流并写入本地文件。
public static String getQrcodeByHttpClient(String realPath,String pusherId){
String url = Global.getConfig("generateQrcodeUrl");
String token = requestWxToken();
if(StringUtils.isBlank(token)){
return null;
}
url = url.replace("ACCESS_TOKEN",token);
//构建http的post请求
CloseableHttpClient client = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(url);
JSONObject paramJson = new JSONObject();
paramJson.put("scene", pusherId);
paramJson.put("page", "pages/index/index");//确保小程序已经发布并且有这个地址
paramJson.put("width", 430);
paramJson.put("is_hyaline", true);
paramJson.put("auto_color", true);
StringEntity entity = new StringEntity(paramJson.toJSONString(), "UTF-8");
httpPost.setEntity(entity);
CloseableHttpResponse response = null;
try {
response = client.execute(httpPost);
HttpEntity httpEntity = response.getEntity();
//开始获取数据
BufferedInputStream bis = new BufferedInputStream(httpEntity.getContent());
String actualpath = "/upload/qr";
//创建目录,首先看目录是否存在不存在先创建
File pathFile = new File(realPath+actualpath);
if(!pathFile.exists()){
pathFile.mkdirs();
}
//写入目标文件
OutputStream os = new FileOutputStream(new File(pathFile.getAbsolutePath()+"/"+pusherId+".jpg"));
int len;
byte[] arr = new byte[1024];
while ((len = bis.read(arr)) != -1)
{
os.write(arr, 0, len);
os.flush();
}
os.close();
return actualpath+"/"+pusherId+".jpg";
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
以上程序需要引入两个jar包
<!-- HttpClient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
<!-- json -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.23</version>
</dependency>