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<String, String> 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或其他打开后可显示异常信息

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值