当前位置:首页 > 编程技术 > Java使用RestTemplate生成微信小程序参数二维码

Java使用RestTemplate生成微信小程序参数二维码

admin2021-10-23 00:06编程技术1210
package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) throws Exception {
//        SpringApplication.run(DemoApplication.class, args);
        DemoApplication.createQrcodeWithScene(1);
    }

    public static void createQrcodeWithScene(Integer uesrId) throws Exception {
        RestTemplate restTemplate = new RestTemplate();
        HashMap forObject = restTemplate.getForObject("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APP_ID&secret=SECRET",
                HashMap.class);
        System.out.println("调用access_token");
        System.out.println(forObject);
        if (forObject == null) {
            throw new Exception("获取access_token接口异常");
        } else {
            Object object = forObject.get("access_token");
            if (object == null) {
                throw new Exception("获取access_token失败");
            } else {
                String accessToken = object.toString();
                HashMap<String, Integer> sceneParam = new HashMap<>();
                sceneParam.put("scene", uesrId);
                ResponseEntity<byte[]> responseEntity = restTemplate.postForEntity(
                        "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken,
                        sceneParam,
                        byte[].class);
                //获取entity中的数据
                byte[] body = responseEntity.getBody();
                //创建输出流  输出到本地
                FileOutputStream fileOutputStream = new FileOutputStream(new File("D:\\1.jpg"));
                if (body == null || body.length == 0) {
                    throw new Exception("二维码返回异常");
                } else {
                    fileOutputStream.write(body);
                    fileOutputStream.close();
                    System.err.println("done");
                }
            }
        }
    }
}


更多:

https://blog.csdn.net/u012702547/article/details/77917939



分享给朋友: