java生成小程序二维码

2019-12-10更新

直接上代码

import com.alibaba.fastjson.JSONObject;
import com.yuboinfo.commom.utils.https.HttpXmlClient;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

/**
 * @author admin
 */
public class XcxQrCode {
    /**
     * 生成二维码
     * Folder:文件夹路径
     * xcxUrl:小程序地址 必须已发布的小程序
     *
     * @param folder 文件夹名称
     * @param xcxUrl 小程序地址
     * @return 地址
     */
    public static String qrCode(String folder,String fileName, String xcxUrl,String appid,String secret) {

        //获取ACCESS_TOKEN
        String accessToken = getAccessToken( appid, secret);
        String name = getQrCode(accessToken, folder, fileName, xcxUrl, 300);
        System.out.println(name);
        return name;
    }

    public static String getAccessToken(String appid,String secret) {
        String requestStr = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=SECRET";
        requestStr = requestStr.replace("APPID", appid);
        requestStr = requestStr.replace("SECRET", secret);
        String oauth2Token = HttpXmlClient.get(requestStr);
        JSONObject jsonObject = JSONObject.parseObject(oauth2Token);
        return jsonObject.getString("access_token");
    }

    public static String getQrCode(String accessToken, String folder,String fileName, String xcxPath, int width) {
        String createwxaqrcodeStr = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=" + accessToken;

        InputStream is = null;
        try {
            JSONObject json = new JSONObject();
            json.put("path",xcxPath);
            json.put("width",width);
            String params = json.toString();
            is = postInputStream(createwxaqrcodeStr, params);
            boolean flag = saveToImgByInputStream(is, folder, fileName);
            if (flag) {
                return folder + "/" + fileName;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(is != null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return "";
    }

    /**
     * 发送HttpPost请求 返回流
     *
     * @param strUrl 服务地址
     * @param params json字符串,例如: "{ \"id\":\"12345\" }" ;其中属性名必须带双引号
* @return 成功:返回json字符串
*/ public static InputStream postInputStream(String strUrl, String params) { try { // 创建连接 URL url = new URL(strUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); // 设置请求方式 connection.setRequestMethod("POST"); // 设置接收数据的格式 connection.setRequestProperty("Accept", "application/json"); // 设置发送数据的格式 connection.setRequestProperty("Content-Type", "application/json"); //创建链接 connection.connect(); // utf-8编码 OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8); out.append(params); out.flush(); out.close(); return connection.getInputStream(); } catch (IOException e) { e.printStackTrace(); } return null; } /** * 将二进制转换成文件保存 * * @param instreams 二进制流 * @param imgPath 图片的保存路径 * @param imgName 图片的名称 * @return 1:保存正常 * 0:保存失败 */ public static boolean saveToImgByInputStream(InputStream instreams, String imgPath, String imgName) { if (instreams != null) { FileOutputStream fos = null; try { createDir(imgPath); //可以是任何图片格式.jpg,.png等 File file = new File(imgPath, imgName); fos = new FileOutputStream(file); byte[] b = new byte[1024]; int nRead; while ((nRead = instreams.read(b)) != -1) { fos.write(b, 0, nRead); } return true; } catch (Exception e) { e.printStackTrace(); } finally { try { if (fos != null) { fos.flush(); fos.close(); } } catch (IOException e) { e.printStackTrace(); } } } return false; } /** * 创建文件夹 * * @param destDirName 文件夹名称 */ public static void createDir(String destDirName) { try { destDirName = URLDecoder.decode(destDirName, "GB2312"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } File dir = new File(destDirName); if (dir.exists()) { System.out.println("创建目录" + destDirName + "失败,目标目录已经存在"); return; } if (!destDirName.endsWith(File.separator)) { destDirName = destDirName + File.separator; } // 创建目录 if (dir.mkdirs()) { System.out.println("创建目录:" + destDirName + "成功!"); } else { System.out.println("创建目录:" + destDirName + "失败!"); } } public static void main(String[] args) { String appid = ""; String secret = ""; qrCode("d:/","adf.png", "pages/index/index",appid,secret); } }

HttpXmlClient.util



import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.jboss.logging.Logger;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author admin
 */
public class HttpXmlClient {
    private static Logger log = Logger.getLogger(HttpXmlClient.class);

    /**
     * 返回请求接口回复的json数据
     *
     * @param url    链接
     * @param params 参数
     * @return String
     */
    public static String post(String url, Map params) {

        //获取DefaultHttpClient请求
        HttpClient httpclient = HttpClientBuilder.create().build();
        log.info("create httppost:" + url);
        HttpPost post = postForm(url, params);
        return invoke(httpclient, post);
    }

    public static String get(String url) {
        HttpClient httpclient = HttpClientBuilder.create().build();
        log.info("create httpget:" + url);
        HttpGet get = new HttpGet(url);
        return invoke(httpclient, get);
    }


    private static String invoke(HttpClient httpclient,
                                 HttpUriRequest httpost) {
        HttpResponse response = sendRequest(httpclient, httpost);
        return paseResponse(response);
    }

    private static String paseResponse(HttpResponse response) {
        log.info("get response from http server..");
        HttpEntity entity = response.getEntity();
        log.info("response status: " + response.getStatusLine());
        String body = null;
        try {
            body = EntityUtils.toString(entity);
            log.info(body);
        } catch (ParseException | IOException e) {
            e.printStackTrace();
        }

        return body;
    }

    private static HttpResponse sendRequest(HttpClient httpclient,
                                            HttpUriRequest httpost) {
        log.info("execute post...");
        HttpResponse response = null;
        try {
            response = httpclient.execute(httpost);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }

    private static HttpPost postForm(String url, Map params) {

        HttpPost httpost = new HttpPost(url);
        List nvps = new ArrayList<>();

        if (params != null) {
            Set keySet = params.keySet();

            for (String key : keySet) {
                nvps.add(new BasicNameValuePair(key, params.get(key)));
            }
            try {
                log.info("set utf-8 form entity to httppost");
                httpost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

        }
        return httpost;
    }
}

 

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