微信公众号获取token,上传素材

Posted 凉城

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了微信公众号获取token,上传素材相关的知识,希望对你有一定的参考价值。

public static JSONObject getToken(String appId,String appSecret){
         String url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appId+"&secret="+appSecret;
         HttpURLConnection con = null;
         BufferedReader bufferedReader=null;
         try {
             URL urlObj = new URL(url);
             // 打开连接
             con = (HttpURLConnection) urlObj.openConnection();
             // 设置请求通用参数
             con.setRequestProperty("accept", "*/*");
             con.setRequestProperty("connection", "Keep-Alive");
             con.connect();
             bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
             
             StringBuffer buffer = new StringBuffer();
             String line = null;
             while ((line = bufferedReader.readLine()) != null) {
                 buffer.append(line);
             }
             String result = buffer.toString();
             JSONObject resultJSON = new JSONObject(result);
             if (resultJSON != null) {
                 System.out.println(resultJSON.toString());
                if(null!=resultJSON.get("access_token")) {
                    return resultJSON;
                }else {
                    throw new Exception("获取微信token失败,APPID="+appId+";微信消息:"+resultJSON.getString("errmsg")+",code="+resultJSON.getString("errcode"));
                }
             }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(null!=con) {
                con.disconnect();
            }
        }
       return null;
    }
    

    
    /**
     * 发送请求
     * @Desc 
     */
    public static  String connectHttpsByPost(String url,String token,String type, String KK, File file) throws Exception {
        if(token==null) {
            token = getToken("1111", "1111").get("access_token").toString();
        }
        String path = "https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=" + token;
        path = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=" + token;
        
        URL urlObj = new URL(path);
        //连接
        HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
        String result = null;
        
        con.setDoInput(true);
        con.setDoOutput(true);
        con.setUseCaches(false);// post方式不能使用缓存

        // 设置请求头信息
        con.setRequestProperty("Connection", "Keep-Alive");
        con.setRequestProperty("Charset", "UTF-8");
        // 设置边界
        String BOUNDARY = "----------" + System.currentTimeMillis();
        con.setRequestProperty("Content-Type", "multipart/form-data; boundary="+ BOUNDARY);

        // 请求正文信息
        // 第一部分:
        StringBuilder sb = new StringBuilder();
        sb.append("--"); // 必须多两道线
        sb.append(BOUNDARY);
        sb.append("
");
        sb.append("Content-Disposition: form-data;name="media";filelength="" + file.length() + "";filename="" + file.getName() + ""
");
        sb.append("Content-Type:application/octet-stream

");
        byte[] head = sb.toString().getBytes("utf-8");
        // 获得输出流
        OutputStream out = new DataOutputStream(con.getOutputStream());
        // 输出表头
        out.write(head);

        // 文件正文部分
        // 把文件已流文件的方式 推入到url中
        DataInputStream in = new DataInputStream(new FileInputStream(file));
        int bytes = 0;
        byte[] bufferOut = new byte[1024];
        while ((bytes = in.read(bufferOut)) != -1) {
            out.write(bufferOut, 0, bytes);
        }
        in.close();
        // 结尾部分
        if(null!=KK) {
            out.write(("--" + BOUNDARY + "
").getBytes());
            out.write("Content-Disposition: form-data; name="description";

".getBytes("utf-8"));
            out.write(String.format("{"title":"%s", "introduction":"%s"}",file.getName(),file.getName()).getBytes("utf-8"));
        }
        byte[] foot = ("
--" + BOUNDARY + "--
").getBytes("utf-8");// 定义最后数据分隔线
        out.write(foot);
        out.flush();
        out.close();
        StringBuffer buffer = new StringBuffer();
        BufferedReader reader = null;
        try {
            // 定义BufferedReader输入流来读取URL的响应
            reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            if (result == null) {
                result = buffer.toString();
            }
        } catch (IOException e) {
            System.out.println("发送POST请求出现异常!" + e);
            e.printStackTrace();
        } finally {
            if (reader != null) {
                reader.close();
            }
        }
        return result;
    }

 

以上是关于微信公众号获取token,上传素材的主要内容,如果未能解决你的问题,请参考以下文章

微信公众号获取图片素材接口

使用 nodeJs 开发微信公众号(上传图片)

微信公众号开发之群发消息

微信小程序同步微信公众号文章(二)

微信公众订阅号 上传临时素材示例

Java 微信公众号上传永久素材的方法