OkHttp上传文件

对接微信的时候,需要通过后台再把图片上传到微信,得到mediaId后再执行后面操作。

图片上传接口

@PostMapping("upload")
public WebResult upload(@RequestParam("img") MultipartFile file) {
    final byte[] bytes;
    try {
        bytes = file.getBytes();
    } catch (IOException e) {
        log.warn("fail to read file", file.getOriginalFilename(), e);
        return new WebResult<>(500, "服务器错误,请稍后再试");
    }
    String md5Hex = DigestUtils.md5Hex(bytes).toUpperCase();
    Map mapToSign = new HashMap<>(8);
    mapToSign.put("mch_id", MCH_ID);
    mapToSign.put("media_hash", md5Hex);
    mapToSign.put("sign_type", "HMAC-SHA256");
    //计算签名
    String sign = SignUtils.createSign(mapToSign, "HMAC-SHA256", MCH_KEY, null);
    
    //构造请求Body
    MultipartBody body = new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart("mch_id", MCH_ID)
            .addFormDataPart("media_hash", md5Hex)
            .addFormDataPart("sign_type", "HMAC-SHA256")
            .addFormDataPart("media", file.getOriginalFilename(), RequestBody.create(MediaType.parse("image/" + FileNameUtil.getExtension(file.getOriginalFilename())), bytes))
            .addFormDataPart("sign", sign)
            .build();
 
    //构造请求
    Request request = new Request.Builder().url("https://api.mch.weixin.qq.com/secapi/mch/uploadmedia")
            .post(body)
            .build();
    OkHttpClient client = new OkHttpClient.Builder()
            .sslSocketFactory(sslManager.getSocketFactory())
            .build();
    //后面的省略了...
}

常见错误

  • 遗漏MultipartBody.FORM:需要设置
setType(MultipartBody.FORM)
  • 签名错误:需要指定签名算法HMAC-SHA256
  • 其他问题:上传到微信的时候,还需要SSL配置,下一篇文章再介绍如何在OkHttp中配置SSL证书

参考

  • how to use okhttp to upload a file?

你可能感兴趣的:(OkHttp上传文件)