java生成小程序码

package com.arvato.service.goods.api.config;

import net.sf.json.JSONObject;
import org.junit.jupiter.api.Test;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Random;

public class Demo {

@Test
public void Text(){
    String code=wxGetQrcode("appid","secret");
    //生成access_token,直接将方法(wxGetQrcode())生成的路径复制到浏览器访问生成access_token赋值到下方
    String url="https://api.weixin.qq.com/wxa/getwxeunlimit?access_token=22_hhpjFnzxKY-MDLbepuY5-_eUlyuefhEvUdrHFZnqfV3QznzkxK7EMS03S4hJe0qe8-mAX2b3pypYzwxtqJJ-vW0jTKudDqw9F1LlpMPG2GAjzSFqG6t2o26QOMphpj9MhE1XcsldAQSycPUZEFMaACAVWD";
    HashMap params = new HashMap<>();
    //scene:参数
    params.put("scene", "id=2771");
    //路径
    params.put("page", "pages/goods/detail/index");
    JSONObject json=JSONObject.fromObject(params);
    String val = "";
    Random random = new Random();
    for (int i = 0; i < 2; i++) {
        val += String.valueOf(random.nextInt(10));
    }
    wxPost(url,json,val);
}

//1.获取ACCESS_TOKEN
public  String wxGetQrcode(String appid, String secret){
    String getQrcode = "https://api.weixin.qq.ci-bin/token?grant_type=client_credential&appid="+ appid + "&secret=" + secret + "";
    return getQrcode;
}
//第二步写入图片
public  void wxPost(String uri, JSONObject paramJson, String fileName) {
    try {
        URL url = new URL(uri);
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setRequestMethod("POST");// 提交模式
        // conn.setConnectTimeout(10000);//连接超时 单位毫秒
        // conn.setReadTimeout(2000);//读取超时 单位毫秒
        // 发送POST请求必须设置如下两行
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setDoInput(true);
        // 获取URLConnection对象对应的输出流
        PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
        printWriter.write(paramJson.toString());
        // flush输出流的缓冲
        printWriter.flush();
        // 开始获取数据
        BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
        System.out.println(bis);
        File file=new File("d:/"+ fileName + ".png");// /Users/shenzhuan/logs/
        OutputStream os = new FileOutputStream(file);
        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 (Exception e) {
        e.printStackTrace();
    }
}

}
当生成图片为1kb是,返回的是异常不是图片信息,删除。png后缀保存,找编译工具:idea或其他打开后可显示异常信息

你可能感兴趣的:(java)