【别问系列】JAVA代码实现 微信小程序 云开发 Http API 上传文件。
别问,看。
过程:
1. JAVA->云环境 请求上传到cos的权限
2. JAVA->COS上传文件
1. 请求上传文件:
String access_token = "你获取的ACCESS_TOKEN"; String url = "https://api.weixin.qq.com/tcb/uploadfile?access_token=" + access_token;// service.getAccessToken(); CloseableHttpClient httpClient = HttpClientBuilder.create().build(); HttpPost httpPost = new HttpPost(url); httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json"); JsonObject req = new JsonObject(); req.addProperty("env", "wxss-brick-dev-9p9ie"); // 云开发环境 从小程序-云开发面板里面找到 req.addProperty("path", "findshop/stores.json"); // 上传的路径,实际上没鸟用,上传文件需要再次指定 StringEntity entity = new StringEntity(req.toString()); httpPost.setEntity(entity); org.apache.http.HttpResponse response1; response1 = httpClient.execute(httpPost); InputStream inputStream = response1.getEntity().getContent(); ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buffer = new byte[8192]; int bytesRead = 0; while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) { out.write(buffer, 0, bytesRead); } out.flush(); out.close(); System.out.println(new String(out.toByteArray()));
这个时候,会获得一个返回JSON:
{ "errcode": 0, "errmsg": "ok", "url": "https:\/\/cos.ap-shanghai.myqcloud.com\/7778-wxss-brick-dev-9p9ie-1257336119\/findshop\/stores.json", "token": "U9AYtVnyBnVM4LiycLOHEdtAeCvV2iza873d0053a37d7e94901ddb969ab51a40SumfJkyblnKjN-u0I8hv-RBNgiLAeS70nsoX0Kq1rfWkBRYEyJ5S55bUpYrbeiIttEbh-E9VqGxW3SeuRwSQ4alQeoa2uHfZQ3oyJochMBWPY3FmV4Vs_heU6EIb8PZpvLzlniE31QVWgJrV0XBlirakVSBXoZLxCYYmZyBk4ixAJCWdvZ91-u4o0hXjVATKAwflK8OE4-7UT6ThJS8d4u39WR34lfLbkV1B4Og7jVxXSz-6xoyeP_YG3DCbsJ7yd_An_MPbc3TT87Jay4mZ_Zg2FK35hJRNZBWcrZpBpuRrTdbNL2rG4Rv5pkwK8AcNxFFS4ZyzoT_qCfwnC5SFtvrQ_dRkhmOkCQiNPdAzUjU", "authorization": "q-sign-algorithm=sha1&q-ak=AKIDHdRV1dId9UIlohYFVT7GDHOP5JF-5Yu-iIMsuT6tLB3N7xgczyLj1I7HiW3gbegH&q-sign-time=1644118512;1644119412&q-key-time=1644118512;1644119412&q-header-list=&q-url-param-list=&q-signature=e2f4e4950426570b76f490dae5fce2cd1564d0ab", "file_id": "cloud:\/\/wxss-brick-dev-9p9ie.7778-wxss-brick-dev-9p9ie-1257336119\/findshop\/stores.json", "cos_file_id": "HHHxuB6f44VmGYFLjPyQISTiYGQLyEsHQLmmNO1ncoimL+YCzQ8WQvFgX7mUOe\/1Z9dGXLrWeiQB1ubjhYUVmoxcKzndW0h+o\/uQxgm3Fh8yG9v1VnNTh6ryJ0Uu00LQ1YxrL8clnzw1NvG\/ftZfMqA5vHEtWo5dAgwnWTw4TuvCIFPIYE\/bSvUSvA==" }
2. 然后利用这个返回JSON再构造一个上传请求:代码紧接上文即可。
req = JsonUtils.toJson(new String(out.toByteArray())).getAsJsonObject(); RestTemplate template = new RestTemplate(); HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentType(org.springframework.http.MediaType.MULTIPART_FORM_DATA); MultiValueMap<String, Object> map = new LinkedMultiValueMap<>(); map.add("key", "helloworld.json"); map.add("Signature", req.get("authorization").getAsString()); map.add("x-cos-security-token", req.get("token").getAsString()); map.add("x-cos-meta-fileid", req.get("cos_file_id").getAsString()); map.add("file", FileUtils.readFileToByteArray((new File("stores.json")))); HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(map, httpHeaders); url = req.get("url").getAsString(); ResponseEntity<Object> responseEntity = template.postForEntity(url, httpEntity, Object.class); System.out.println(responseEntity);
得到一个返回:
[Content - Length: "0",
Connection: "keep-alive",
Date: "Sun, 06 Feb 2022 04:55:23 GMT",
ETag: ""
9 f984a7876e8a9ba68b33e4ce9fa6e07 "",
Location: "http://cos.ap-shanghai.myqcloud.com/helloworld.json",
Server: "tencent-cos",
x - cos - hash - crc64ecma: "15603994211910412157",
x - cos - request - id: "NjFmZjU0YmFfNjFhMDA4MDlfMTQ3YjdfMjZlNzRkNg=="
]
全部完成!
相关资料:
1. 官方和屎一样的垃圾文档:https://developers.weixin.qq.com/miniprogram/dev/wxcloud/reference-http-api/storage/uploadFile.html
2. 一个很有用的成功案例:https://developers.weixin.qq.com/community/develop/doc/0006ca8d9b866842a10a7f20a51000