java图片链接转文件&上传到微信服务

把媒体文件上传到微信服务器,微信api

背景:业务需求是在公众号里自动回复二维码图片,自动回复用的图片事先已经上传至公司文件服务器;以下是执行成功代码

1、将图片链接转换成文件

private File getFileByUrl(String picUrl, String suffix) throws Exception {
        URL imageUrl = new URL(picUrl);
        HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
        InputStream inputStream = conn.getInputStream();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, len);
        }
        File file = File.createTempFile("pattern", "." + suffix);
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        fileOutputStream.write(outputStream.toByteArray());

        inputStream.close();
        outputStream.close();
        fileOutputStream.close();
        return file;
    }

2、上传至微信服务器

public String doPostWithFormData(String url, File file, String fileType, String paramName) {
        RequestBody fileBody = RequestBody.create(MediaType.parse(fileType), file);
        RequestBody multipartBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart(paramName, file.getName(),fileBody)
                .build();

        Request request = new Request.Builder()
                .url(url)
                .post(multipartBody)
                .build();
        return getResult(request);
    }
private String getResult(Request request) {
        if (null == request) {
            log.error("http 请求 request 不能为 null");
            return null;
        }
        String message = null;
        long beginTime = System.nanoTime();
        try {
            Response response = client.newCall(request).execute();
            if (response.body() != null) {
                message = response.body().string();
            }
        } catch (Exception e) {
            log.error(" 请求 {} , 执行时间 : {}, 报错{}", request.toString(), TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - beginTime),  e);
        }
        log.info(" 请求 {} , 执行时间 : {}", request.toString(), TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - beginTime));
        return message;
    }

3、调用

public String uploadTempImage(String picUrl){
        if (StringUtils.isBlank(picUrl)) {
            return null;
        }

        String accessToken = "";// 公司的accessToken
        String url = "https://api.weixin.qq.com/cgi-bin/media/upload?type=image&access_token=" + accessToken;

        String result = null;
        try {
            String suffix = picUrl.substring(picUrl.lastIndexOf(".")+1, picUrl.length());
            File file = getFileByUrl(picUrl, suffix);
            String fileType = "image/jpeg";
            if ("png".equalsIgnoreCase(suffix)) {
                fileType = "image/png";
            }

            result = HttpClientUtils.getInstance().doPostWithFormData(url, file, fileType, "media");
            file.delete();
        } catch (Exception e) {
            log.warn("uploadTempImage,failed", e);
        }

        log.info("uploadTempImage,result={}", result);

        return Optional.ofNullable(result)
                .map(s -> JsonUtils.toBean(s, Map.class))
                .map(map -> (String)map.get("media_id")).orElse(null);
    }

4、遇到的问题

(1){“errcode”:41005,“errmsg”:“media data missing hint: [ZiYG1a0115d418]”}
可能原因:传参时方法错误,错误方法 addPart(fileBody)
我的解决:.addFormDataPart(paramName, file.getName(),fileBody)
文件参数名传空也行
(2)java media data missing hint: [hPxMUa0729hb93]
这个稀里糊涂就解决了,后来也没试出是哪里错了

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值