1、微信文档说明
ps:有关微信的一些文档说明我真的是服了,这个文档,抛出来看的人真的是一头雾水,算了,我也不做过多评判;下面看我调用的示例代码
2、示例代码
/**
* 上传pdf
* https://api.weixin.qq.com/card/invoice/platform/setpdf?access_token={access_token}
* form-data中媒体文件标识,有filename、filelength、content-type等信息
* ------WebKitFormBoundary2exwM16BY25kVBgf
* Content-Disposition: form-data;
* name="pdf";
* filename="1133090578170938.pdf"
* Content-Type: application/pdf Pdf content
* ------WebKitFormBoundary2exwM16BY25kVBgf—
* 返回:
* {
* "errcode":0,
* "errmsg":"ok",
* "s_media_id":"3015806758683707"
* }
*
* @param pdf
* @return
*/
@Override
public String setPdf(MultipartFile pdf) {
String token = "自行获取token";
String url = String.format("https://api.weixin.qq.com/card/invoice/platform/setpdf?access_token=%s", token);
try {
String result = this.uploadPDF(url, pdf);
if (StringUtils.isNotEmpty(result)) {
JSONObject jsonObject = JSONObject.parseObject(result);
if (jsonObject.getInteger("errcode") == 0) {
return jsonObject.getString("s_media_id");
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return null;
}
/**
* 上传pdf到微信
*
* @param url
* @param pdfFile
* @return
* @throws Exception
*/
private String uploadPDF(String url, MultipartFile pdfFile) throws Exception {
// 构造上传PDF的请求
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("pdf", pdfFile.getOriginalFilename(),
RequestBody.create(MediaType.parse("application/pdf"), pdfFile.getBytes()))
.build();
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
// 发送请求,获取响应
Response response = new OkHttpClient().newCall(request).execute();
if (response.isSuccessful()) {
String result = response.body().string();
return result;
} else {
throw new Exception(String.format("请求 %s 未成功,错误代码:%s", url, response.code()));
}
}