package vip.xiaonuo.biz.core.utils;

import cn.hutool.core.io.IoUtil;
import com.alibaba.fastjson.JSONObject;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class WxUtil {
    public static InputStream postInputStream(String urlStr , JSONObject paramJson) throws Exception {
        //获取小程序码，适用于需要的码数量较少的业务场景。通过该接口生成的小程序码，永久有效，有数量限制
        URL url = new URL(urlStr);

        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setRequestMethod("POST");// 提交模式
        // 发送POST请求必须设置如下两行
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setDoInput(true);
        // 获取URLConnection对象对应的输出流
        PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());

        printWriter.write(paramJson.toString());
        // flush输出流的缓冲
        printWriter.flush();
        String contentType = httpURLConnection.getContentType();
        if (contentType.contains("json")) {
            IoUtil.copy(httpURLConnection.getInputStream(), System.out);
            throw new IllegalArgumentException("调用微信小程序生成接口出错");
        } else {
            //开始获取数据
            return  httpURLConnection.getInputStream();
        }
    }
}
