微信小程序码的生成(java)

一,准备util类

public class WXUtils {
//获取token信息 
public static String getToken(String tokenUrl,String wxappid,String wxappsecret) throws ClientProtocolException,IOException {
String access_token = null;
String tokenUrlReq = tokenUrl.replaceAll("WXAPPID", wxappid).replaceAll("WXAPPSECRET", wxappsecret);
        HttpGet httpGet = new HttpGet(tokenUrlReq);
        HttpClient httpClient = HttpClients.createDefault();
        HttpResponse res = httpClient.execute(httpGet);
        HttpEntity entity = res.getEntity();
        String result = EntityUtils.toString(entity, "UTF-8");
        JSONObject jsons = JSONObject.fromObject(result);
        String expires_in = jsons.getString("expires_in");
        //缓存
        if(Integer.parseInt(expires_in)==7200){
            //ok
            access_token = jsons.getString("access_token");
        }else{
            System.out.println("出错获取token失败!");
        }
        return access_token;
    }

}


获取access_token :

String access_token = WXUtils.getToken(tokenUrl, wxappid, wxappsecret);

String qrCode = centerCode+'_'+autoGenericCode(i+"",3);(生成的个数可以for循环,主要方法是autoGenericCode()方法,其它为区分标识)


/**

     *autoGenericCode

     * 不够位数的在前面补0,保留num的长度位数字
     * @param code
     * @return
     */
    private String autoGenericCode(String code, int num) {
        String result = "";
        result = String.format("%0" + num + "d", Integer.parseInt(code) );
        return result;

    }

//GetPostUrl

 public String GetPostUrl(String access_token,String centerCode,String qrCode) throws Exception {
String url = createcodeUrl+access_token;
         Map<String,Object> param = new HashMap<String, Object>();
         param.put("scene", qrCode);
         param.put("page", qrcodePage);  //qrcodePage为指定的跳转页面
         param.put("width", 430);
         param.put("auto_color", false);
         Map<String,Object> line_color = new HashMap<String, Object>();
         line_color.put("r", 0);
         line_color.put("g", 0);
         line_color.put("b", 0);
         param.put("line_color", line_color);
        
         JSONObject json = JSONObject.fromObject(param);
         String res = httpPostWithJSON(url,json.toString(),centerCode,qrCode);
         return res;

}




 //返回图片保存 ,根据 id 
public String httpPostWithJSON(String url, String json,String centerCode,String qrCode) throws Exception {
//生成二维码编号区别
String nowTime = DateUtils.getDateTimeNoFormat();
String fileName = qrCode+"_"+nowTime+".png";
String filePath = imageRootPath+"/"+qrcodePath+"/";
        String result = fileName;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Content-Type", "application/json");
   
        StringEntity se = new StringEntity(json);
        se.setContentType("application/json");
        se.setContentEncoding(new BasicHeader("Content-Type", "UTF-8"));
        httpPost.setEntity(se);
        
        CloseableHttpResponse response = httpClient.execute(httpPost);
        if (response != null) {
        org.apache.http.HttpEntity resEntity = response.getEntity();
            if(resEntity != null) {
            InputStream instreams = resEntity.getContent(); 
                File saveFile = new File(filePath+fileName);
                // 判断这个文件(saveFile)是否存在
                if (!saveFile.getParentFile().exists()) {
                // 如果不存在就创建这个文件夹
                saveFile.getParentFile().mkdirs();
                }
                saveToImgByInputStream(instreams, filePath,fileName);
            }
        }
        httpPost.abort();
        return result;



 /* @param instreams 二进制流
    * @param imgPath 图片的保存路径
    * @param imgName 图片的名称
    * @return
    *      1:保存正常
    *      0:保存失败
    */
public static int saveToImgByInputStream(InputStream instreams,String imgPath,String imgName){
int stateInt = 1;
ByteArrayOutputStream outStream = null;
FileOutputStream fos = null;
    if(instreams != null){
    try {
    outStream = new ByteArrayOutputStream(); 
    //创建一个Buffer字符串 
            byte[] buffer = new byte[1024]; 
            //每次读取的字符串长度,如果为-1,代表全部读取完毕 
            int len = 0; 
            //使用一个输入流从buffer里把数据读取出来 
            while( (len=instreams.read(buffer)) != -1 ){ 
            //用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度 
            outStream.write(buffer, 0, len); 
            } 
            //关闭输入流 
            //instreams.close(); 
            //把outStream里的数据写入内存 
            byte[] data = outStream.toByteArray();
            File file = new File(imgPath+imgName);//可以是任何图片格式.jpg,.png等
            fos = new FileOutputStream(file);
            fos.write(data); 
            fos.flush();
    } catch (Exception e) {
    stateInt = 0;
    e.printStackTrace();
        } finally {
        try {
        if(fos!=null){
        fos.close();
        }
        if(outStream!=null){
        outStream.close();
        }
        } catch (IOException e) {
        e.printStackTrace();
        }
       }
    }
    return stateInt;
}

猜你喜欢

转载自blog.csdn.net/qq_25161679/article/details/80623809