java 后台获取微信小程序二维码保存至本地

首先获取token

获取微信token 接口

https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Get_access_token.html

/**
 * 获取token
 * @param appId
 * @param secret
 * @return
 */
public String getWxToken(String appId,String secret){
    String accessTokenUrl ="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appId+"&secret="+secret;
    String tokenJson = WeixinUtil.httpRequest(accessTokenUrl, "GET", null);
    JSONObject jsonObject = JSONObject.parseObject(tokenJson);
    String token = jsonObject.getString("access_token");
    System.out.println("获取token -----" +  token);
    return token;
}

发起请求获取响应返回token字符串

/**
 * 发起https请求并获取结果
 *
 * @param requestUrl 请求地址
 * @param requestMethod 请求方式(GET、POST)
 * @param outputStr 提交的数据
 * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
 */
public static String httpRequest(String requestUrl, String requestMethod, String outputStr) {

    StringBuffer buffer = new StringBuffer();
    try {
        // 创建SSLContext对象,并使用我们指定的信任管理器初始化
        TrustManager[] tm = { new MyX509TrustManager() };
        SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
        sslContext.init(null, tm, new java.security.SecureRandom());
        // 从上述SSLContext对象中得到SSLSocketFactory对象
        SSLSocketFactory ssf = sslContext.getSocketFactory();

        URL url = new URL(requestUrl);
        HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
        httpUrlConn.setSSLSocketFactory(ssf);
        httpUrlConn.setDoOutput(true);
        httpUrlConn.setDoInput(true);
        httpUrlConn.setUseCaches(false);
        // 设置请求方式(GET/POST)
        httpUrlConn.setRequestMethod(requestMethod);

        if ("GET".equalsIgnoreCase(requestMethod))
            httpUrlConn.connect();

        // 当有数据需要提交时
        if (null != outputStr) {
            OutputStream outputStream = httpUrlConn.getOutputStream();
            // 注意编码格式,防止中文乱码
            outputStream.write(outputStr.getBytes("UTF-8"));
            outputStream.close();
        }

        // 将返回的输入流转换成字符串
        InputStream inputStream = httpUrlConn.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);


        String str = null;
        while ((str = bufferedReader.readLine()) != null) {
            buffer.append(str);
        }
        bufferedReader.close();
        inputStreamReader.close();
        // 释放资源
        inputStream.close();
        inputStream = null;
        httpUrlConn.disconnect();
        return buffer.toString();
    } catch (ConnectException ce) {
        ce.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "";
}

接下来获取小程序二维码图片并且保存至本地

public Object getQrcodeImage(Map params){
    //token上面获取替换
    String accessToken = "35_khk5XKRQOV4AAlJ19AOB5DqNQp4uP_4npj6vPMkixg4FsQF5LiU1j3wv-t8I397jM590_Q8TjAGYKvPOlZTgiKywGymbt5eL01m1or7bBVI_WAXKWDiPMnwpoqeNMpE_E6h6RfQB509sc5t_LRJgAGAHNF";  
    String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+accessToken;
    String body = JSONObject.toJSONString(params); //转换为json字符串
    WeixinUtil.post(url,body,"aa");
  return null;
}

注意参数:java 后台获取微信小程序二维码保存至本地_第1张图片

发情请求获取响应文件流。

/**
 * 测试获取微信小程序二维码
 * @param requestUrl
 * @param paramJson
 * @param fileName
 */
public static void post(String requestUrl, String paramJson, String fileName) {
    try {
        URL url = new URL(requestUrl);
        HttpURLConnection httpURLConnection = (HttpURLConnection) url
                .openConnection();
        httpURLConnection.setRequestMethod("POST");// 提交模式
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setDoInput(true);
        PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
        printWriter.write(paramJson);
        // flush输出流的缓冲
        printWriter.flush();
        // 开始获取数据
        BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
        OutputStream os = new FileOutputStream(new File("D:/upload/"+ fileName + ".png"));
        int len;
        byte[] arr = new byte[1024];
        while ((len = bis.read(arr)) != -1) {
            os.write(arr, 0, len);
            os.flush();
        }
        os.close();
        bis.close();
    } catch (ConnectException ce) {
        ce.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
执行完之后就可以在本地文件上查看生成得小程序码了
java 后台获取微信小程序二维码保存至本地_第2张图片

 

 

 

 

记录一下

 

你可能感兴趣的:(java,小程序)