@ApiOperation(value = "获取小程序二维码")
@PostMapping(value = "/getCode")
public SuccessOutPut<String> getCode(@RequestBody CodesInput code,HttpServletRequest request) {
StringBuffer backUrl = new StringBuffer(); // 回调url
String fileName = UUID.randomUUID().toString() + System.currentTimeMillis()+ (".jpg");
try {
StringBuffer info = new StringBuffer("https://api.weixin.qq.com/wxa/getwxacodeunlimit?");
URL url = null;
String accessToken = AccessToken.getAccessToken();
if (null != accessToken) {
url = new URL(info.append("access_token=").append(accessToken).toString());
} else {
String accessToken2 = AccessToken.getAccessToken();
url = new URL(info.append("access_token=").append(accessToken2).toString());
}
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");// 提交模式
httpURLConnection.setRequestProperty("Content-type", "application/json");
// conn.setConnectTimeout(10000);//连接超时 单位毫秒
// conn.setReadTimeout(2000);//读取超时 单位毫秒
// 发送POST请求必须设置如下两行
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
// 获取URLConnection对象对应的输出流
PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
// 发送请求参数
JSONObject paramJson = new JSONObject();
paramJson.put("scene", code.getScene());
paramJson.put("page", code.getPage());
paramJson.put("width", 430);
printWriter.write(paramJson.toString());
// flush输出流的缓冲
printWriter.flush();
//开始获取数据
BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
//buff用于存放循环读取的临时数据
byte[] buff = new byte[100];
int rc = 0;
while ((rc = bis.read(buff, 0, 100)) > 0) {
swapStream.write(buff, 0, rc);
}
ByteArrayInputStream inputStream= new ByteArrayInputStream(swapStream.toByteArray());
BufferedImage image = ImageIO.read(inputStream);
/**裁剪原图 目前访问微信 微信返回的是 470*535 像素 170620*/
BufferedImage subImage = image.getSubimage(0, 0, image.getWidth(), image.getHeight());
BufferedImage inputbig = new BufferedImage(430, 430, BufferedImage.TYPE_INT_BGR);
Graphics2D g = (Graphics2D) inputbig.getGraphics();
g.drawImage(subImage, 0, 0,430,430,null); //画图
g.dispose();
inputbig.flush();
ImageIO.write(inputbig, "jpg", new File("/home/images/"+fileName));
} catch (Exception e) {
e.printStackTrace();
}
StringBuffer append = backUrl.append(getBackUrl(getServerIPPort(request), fileName));
return new SuccessOutPut<>(append.toString());
来源:CSDN
作者:Ais永恒
链接:https://blog.csdn.net/xinxin172170185/article/details/87936852