1、二维码生成
package com.vmanager.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.vmanager.WebApplication;
import lombok.val;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
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.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.boot.SpringApplication;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
public class test {
public static void main(String[] args) throws IOException {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// 创建Get请求
//我的小程序
HttpGet httpGet = new HttpGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=xxxxxx&secret=xxxxxx");
// 响应模型
CloseableHttpResponse response = null;
response = httpClient.execute(httpGet);
// 从响应模型中获取响应实体
HttpEntity responseEntity = response.getEntity();
String json = EntityUtils.toString(responseEntity);
System.out.println("响应内容为:" + json);
Map<String, Object> parse = (Map<String, Object>) JSON.parse(json);
val access_token = parse.get("access_token");
System.out.println("access_token:" + access_token);
HttpPost post = new HttpPost("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + access_token);
post.setHeader("Content-Type", "application/json;charset=utf-8");
post.setHeader("Accept", "application/json;charset=utf-8");
JSONObject params = new JSONObject();
params.put("scene", "=fyu-001&itemId=442");
// params.put("page", "pages/chufei/law/lawDetail");
// params.put("page", "pages/logs/logs");
String str = params.toJSONString();
StringEntity stringEntity = new StringEntity(str, "utf-8");
post.setEntity(stringEntity);
response = null;
response = httpClient.execute(post);
String result = null;
//获取结果实体并返回结果
HttpEntity entity = response.getEntity();
InputStream inputStream = response.getEntity().getContent();
String name = "guoran.png";
saveToImgByInputStream(inputStream, "D:\\", name); //保存图片
}
/**
* 将二进制转换成文件保存
*
* @param instreams 二进制流
* @param imgPath 图片的保存路径
* @param imgName 图片的名称
* @return 1:保存正常
* 0:保存失败
*/
public static int saveToImgByInputStream(InputStream instreams, String imgPath, String imgName) {
int stateInt = 1;
if (instreams != null) {
try {
File file = new File(imgPath, imgName);//可以是任何图片格式.jpg,.png等
FileOutputStream fos = new FileOutputStream(file);
byte[] b = new byte[1024];
int nRead = 0;
while ((nRead = instreams.read(b)) != -1) {
fos.write(b, 0, nRead);
}
fos.flush();
fos.close();
} catch (Exception e) {
stateInt = 0;
e.printStackTrace();
} finally {
}
}
return stateInt;
}
}
2、二维码识别
在小程序端实现:
scene是根据参数值确定的,也可以: