V3版SDK进件接口上传图片
图片上传步骤:
1.创建一个POST的方法请求/upload URI
例如: POST https://api.mch.weixin.qq.com/v3/merchant/media/upload HTTP/1.1
2.将文件的数据添加到请求主体
2.1 图片文件file参数的获取方式说明:
媒体图片二进制内容,放在请求http的body中。
2.2 媒体文件元信息meta参数的获取方式说明:
媒体文件元信息,使用json表示,包含两个对象:filename、sha256。
● filename参数获取方式说明:
商户上传的媒体图片的名称,商户自定义,必须以JPG、BMP、PNG为后缀。
● sha256参数获取方式说明:
图片文件的文件摘要,即对图片文件的二进制内容进行sha256计算得到的值。
public String upload(String method, String domainUrl,String filepath) throws IOException, NoSuchAlgorithmException, KeyStoreException, SignatureException, InvalidKeyException {
String nonceStr=getRandomString(32);
long timestamp=getTimestamp();
URL uri = new URL(domainUrl);
String canonicalUrl = uri.getPath();
if (uri.getQuery() != null) {
canonicalUrl += "?" + uri.getQuery();
}
File file = new File(filepath);
String filename=file.getName();
String hex= DigestUtil.sha256Hex(file);
String metaJson="{\"filename\":\""+filename+"\",\"sha256\":\""+hex+"\"}";
String signature=getSignature(method,canonicalUrl,metaJson,nonceStr,timestamp);
String authorization="mchid=\"" + wxMchServerConfig.getMchId() + "\","
+ "nonce_str=\"" + nonceStr + "\","
+ "timestamp=\"" + timestamp + "\","
+ "serial_no=\"" + wxMchServerConfig.getSerialNo() + "\","
+ "signature=\"" + signature + "\"";
Map headers=new HashMap<>();
headers.put("Authorization","WECHATPAY2-SHA256-RSA2048"+" "+authorization);
headers.put("User-Agent","WechatPay-TEST-HttpClient");
headers.put("Content-Type" ,"multipart/form-data;boundary=\"boundary\"");
HttpResponse response = HttpRequest.post(domainUrl)
.addHeaders(headers)
.form("file",file)
.form("meta",metaJson)
.execute();
String respbody=response.body();
return respbody;
}