java开发微信订阅号群发功能(一)

在进行订阅号的群发功能时第一步就是要获取access_token这个在之后的接口中都要用到这个参数 以下是access_token的介绍:

在获取access_token时需要传递的参数是需要转换json的在代码注释中有体现

发送请求的工具类如下:

package com.zm.mall.util.wechatutil;

/**
 * Creat0ed by Administrator on 2020/4/29.
 */

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.net.HttpURLConnection;
import javax.net.ssl.HttpsURLConnection;

import net.sf.json.JSONObject;
public class HttpsUtil {
    /**
     * HttpsUtil方法https请求结果返回蔚json类型
     * @param Url http请求地址
     * @param Method http请求类型支持POST GET
     * @param Output
     * @return InputStream转换成JSONObject后返回
     * @throws Exception
     */
    public JSONObject HttpsUtil(String Url,String Method,String Output) throws Exception{
        JSONObject jsonObject = null;
        URL conn_url =  new URL(Url);
        HttpURLConnection conn = (HttpsURLConnection)conn_url.openConnection();
        conn.setRequestMethod(Method);
        conn.setReadTimeout(5000);
        conn.setConnectTimeout(5000);
        conn.connect();
        //output获取access_token是不会用到
//        if(Output != null){
//            OutputStream  outputstream =conn.getOutputStream();
//            //字符集,防止出现中文乱码
//            outputstream.write(Output.getBytes("UTF-8"));
//            outputstream.close();
//        }
        //正常返回代码为200
        if(conn.getResponseCode()==200){
            InputStream stream = conn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(stream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            stream.close();
            conn.disconnect();
            jsonObject = JSONObject.fromObject(buffer.toString());
        }
        System.out.println(conn.getResponseCode());
        return jsonObject;
    }
}

这样就可以获取到access_token了

至于怎么获取APPID和APPSECRET可以看看这个链接: https://www.jb51.net/yunying/166336.html

经验分享 程序员 微信小程序 职场和发展