Java方式实现上传微信素材

微信官方给出的例子仅仅是使用curl上传的本地资源,以下提供了一种模拟的请求方式去在代码中上传

 		byte[] fileBytes = "your file bytes";
        String filename = "your file name";
        String accessToken = "your wx access token";
        String type = "iamage";
        URL url = new URL(String.format("https://api.weixin.qq.com/cgi-bin/media/upload?access_token=%s&type=%s", accessToken, type));

        // 创建Http连接
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);

        // 消息请求头信息
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Charset", "UTF-8");

        // 设置开始边界
        String BOUNDARY = "----------" + System.currentTimeMillis();
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDARY);

        String sb = "--" + BOUNDARY + "\r\n" +
                "Content-Disposition:form-data;name=\"media\";filename=\"" + filename + "\";filelength=\"" + fileBytes.length + "\"\r\n" +
                "Content-Type:application/octet-stream\r\n\r\n";
        byte[] head = sb.getBytes(StandardCharsets.UTF_8);

        // 创建输出流
        OutputStream out = new DataOutputStream(conn.getOutputStream());
        out.write(head);

        DataInputStream in = new DataInputStream(new ByteArrayInputStream(fileBytes));
        int bytes;
        byte[] bufferOut = new byte[1024];
        while ((bytes = in.read(bufferOut)) != -1) {
            out.write(bufferOut, 0, bytes);
        }
        in.close();

        // 设置结束边界
        byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes(StandardCharsets.UTF_8);
        out.write(foot);
        out.flush();
        out.close();

        StringBuilder buffer = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
            // 读取响应
            String line;
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
        } catch (Exception e) {
            logger.warn("upload wx material error.", e);
        }
 		//打印结果
        System.out.println(JSON.toJSONString(result));
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值