package com.bgs.web;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;import com.bgs.utils.HttpRequest;
import net.sf.json.JSONObject;
@Controller
public class GetWXACodeController {
//生成带参数的小程序码getQrcode
@RequestMapping(value="/getQrcode",produces="application/json;charset=UTF-8")
@ResponseBody
public String getQrcode(String page,String scene,Integer width) {
//1.先获取access_token
String sr = HttpRequest.sendGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=自己的appid&secret=自己的密钥");
JSONObject json = JSONObject.fromObject(sr);
String accessToken = json.get("access_token").toString();
//2.生成二维码
try
{
URL url = new URL("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+accessToken);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");// 提交模式
// 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", scene);
paramJson.put("page", page);
paramJson.put("width", width);
paramJson.put("auto_color", true);
/**
* line_color生效
* paramJson.put("auto_color", false);
* JSONObject lineColor = new JSONObject();
* lineColor.put("r", 0);
* lineColor.put("g", 0);
* lineColor.put("b", 0);
* paramJson.put("line_color", lineColor);
* */printWriter.write(paramJson.toString());
// flush输出流的缓冲
printWriter.flush();
//开始获取数据
BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
OutputStream os = new FileOutputStream(new File("生成图片的位置"));
int len;
byte[] arr = new byte[1024];
while ((len = bis.read(arr)) != -1)
{
os.write(arr, 0, len);
os.flush();
}
os.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return "";
}
}
生成微信小程序二维码
最新推荐文章于 2023-12-21 10:39:27 发布