http.sync("/upload")
.addFileParam("test", "D:/download/test.zip")
.post() // 上傳發(fā)法一般使用 POST 或 PUT,看服務(wù)器支持
異步上傳也是完全一樣:
http.async("/upload")
.addFileParam("test", "D:/download/test.zip")
.post()
對(duì)接微信的時(shí)候,需要通過(guò)后臺(tái)再把圖片上傳到微信,得到 mediaId 后再執(zhí)行后面操作。
@PostMapping("upload")
public WebResult<ImageUploadResult> 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, "服務(wù)器錯(cuò)誤,請(qǐng)稍后再試");
}
String md5Hex = DigestUtils.md5Hex(bytes).toUpperCase();
Map<String, String> mapToSign = new HashMap<>(8);
mapToSign.put("mch_id", MCH_ID);
mapToSign.put("media_hash", md5Hex);
mapToSign.put("sign_type", "HMAC-SHA256");
//計(jì)算簽名
String sign = SignUtils.createSign(mapToSign, "HMAC-SHA256", MCH_KEY, null);
//構(gòu)造請(qǐng)求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();
//構(gòu)造請(qǐng)求
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
:需要設(shè)置setType(MultipartBody.FORM)
HMAC-SHA256
更多建議: