- 简单粗暴,直接开干,获取 access_token
public String getAccessToken() {
try {
StringBuilder url = new StringBuilder("https://api.weixin.qq.com/cgi-bin/token?");
//固定参数
url.append("grant_type=").append("client_credential");
//微信小程序的appId和secret
url.append("&appid=").append(appId);
url.append("&secret=").append(appSecret);
HttpClient client = HttpClientBuilder.create().build();//构建一个Client
HttpGet get = new HttpGet(url.toString()); //构建一个GET请求
HttpResponse response = client.execute(get);//提交GET请求
HttpEntity he = response.getEntity();//拿到返回的HttpResponse的"实体"
String content = EntityUtils.toString(he);
JSONObject obj = JSONObject.parseObject(content);
return obj.getString("access_token");
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
/**
* 二维码图片生成
*/
public String getQrCode(String codeName, String shopId) {
InputStream inputStream = null;
try {
Map<String, Object> map = new HashMap<>();
//参数,一个可以直接放入参数例如:1 多个例如:id=1&name=2&...,注意,参数长度不能大于32位
map.put("scene", shopId);
map.put("path", "pages/warrant/warrant"); //扫码后进入小程序的页面位置
map.put("width", 430);//不是必须,需要的宽度,默认430x430,最小280最大1280
map.put("is_hyaline", true);//是否透明底色
map.put("auto_color", false);//是否线条变色,auto_color=false 生效
map.put("line_color", JSONUtil.toBean("{'r':255,'g':0,'b':0}", Object.class));
String body = JSON.toJSONString(map);//将map集合转换成字符串
StringEntity entity = new StringEntity(body);
entity.setContentType("image/jpeg");//设置图片类型
String token = getAccessToken();//获取access_token
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + token);
httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
httpPost.setEntity(entity);
HttpResponse httpResponse = httpClient.execute(httpPost);
inputStream = httpResponse.getEntity().getContent();
//文件名加后缀,文件后缀要一致
String name = codeName + ".jpg";
downLoad(inputStream, name);
return osspath;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 生成在本地
* @param name
* @param input
* @throws IOException
*/
public static void writeToLocal(String name, InputStream input) throws IOException {
int index;
byte[] bytes = new byte[1024];
FileOutputStream downloadFile = new FileOutputStream("H:\\photo\\" + name);
while ((index = input.read(bytes)) != -1) {
downloadFile.write(bytes, 0, index);
downloadFile.flush();
}
input.close();
downloadFile.close();
}
![](https://i-blog.csdnimg.cn/blog_migrate/9f25902fcd10ae7a908cd7116d8a74ac.png)