Skip to content

Instantly share code, notes, and snippets.

@gjp0609
Created January 17, 2019 02:26
Show Gist options
  • Save gjp0609/626515fd3b25e6605d723601e1c692d6 to your computer and use it in GitHub Desktop.
Save gjp0609/626515fd3b25e6605d723601e1c692d6 to your computer and use it in GitHub Desktop.
generic WXAQRCode
/**
* 生成小程序二维码并存入本地
*
* @param pathAndParams 路径及自定义参数: /page/index?id=123
* @param filePathAndName 文件路径及名称: C:/Files/qrcode/123.jpg
*/
private static void generic(String pathAndParams, String filePathAndName) {
RestTemplate rest = new RestTemplate();
InputStream inputStream = null;
OutputStream outputStream = null;
try {
String url = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=" + accessToken;
Map<String, Object> param = new HashMap<>();
param.put("path", pathAndParams);
param.put("width", 430);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(param, headers);
ResponseEntity<byte[]> entity = rest.exchange(url, HttpMethod.POST, httpEntity, byte[].class);
byte[] result = entity.getBody();
inputStream = new ByteArrayInputStream(result);
File file = new File(filePathAndName);
if (!file.exists()) {
boolean newFile = file.createNewFile();
if (!newFile) {
System.err.println("创建文件失败:" + file.getAbsolutePath());
return;
}
}
outputStream = new FileOutputStream(file);
int len;
byte[] buf = new byte[1024];
while ((len = inputStream.read(buf, 0, 1024)) != -1) {
outputStream.write(buf, 0, len);
}
outputStream.flush();
} catch (Exception e) {
System.out.println("生成二维码异常");
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment