java obtains the QR code of wechat applet and returns the picture

1. Get access_token. I won't talk about how to get it!

See this article:

 * Get the QR code of wechat
 * @return
 * @return Object
 * @author tyg
 * @date   2020 5:35:07 PM, February 6, 2015
@RequestMapping(value = "/wechat/getWechatqr", method = RequestMethod.GET)
public void getWechatqr(String scene, Integer width, HttpServletResponse response) {
	JSONObject jsonObject = new JSONObject();
	jsonObject.put("scene", scene);
	jsonObject.put("width", width == null ? 430 : width);
	InputStream inputStream = HttpUtil.sendPostBackStream(""+wechatI.getAccessToken(), jsonObject.toJSONString());
	try {
		BufferedImage bi;
		ImageIO.write(bi, "PNG", response.getOutputStream());
	} catch (IOException e) {
	} finally {
 * Send a request for the POST method to the specified URL
 * @param url   URL to send the request
 * @param param Request parameters
 * @return Response result of the remote resource represented
public static InputStream sendPostBackStream(String url, String param) {
	PrintWriter out = null;
	try {
		URL realUrl = new URL(url);
		// Open connection to URL
		URLConnection conn = realUrl.openConnection();
		// Set common request properties
		conn.setRequestProperty("accept", "*/*");
		conn.setRequestProperty("connection", "Keep-Alive");
				"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
		//Solve the problem of garbled code
		OutputStreamWriter outWriter =new OutputStreamWriter(conn.getOutputStream(), "utf-8");
		out =new PrintWriter(outWriter);
		// Send request parameters
		if(StringUtils.isNotBlank(param)) {
		// Buffer of flush output stream
		return conn.getInputStream();
	} catch (Exception e) {
		System.out.println("Send out POST Exception in request!"+e);
	} finally{
	return null;

2. Problems encountered

Access_token expired: {"errcode":42001,"errmsg":"access_token expired hints: [sadAve4MRa-g.elLA!]"}

Solution: get access_token again


The incoming data format is incorrect: {"errcode":47001,"errmsg":"data format error hint: [LuKkxa06781511]]}

The parameter I passed in here is scene = a = 1 & width = 430. Actually, it should be json format, {"scene":"a=1","width":"430"}. There may be other situations. What I have here is this.

Let me show you the renderings.

Happy new year, novel coronavirus pneumonia, away from crowds, wearing masks, family Ping Pingan Ann!

Tags: Programming Windows JSON

Posted on Mon, 23 Mar 2020 09:04:58 -0700 by akjackson1