現在都流行直播帶貨,所以我公司作為一家零售行業公司,自然而且也要更上步伐。於是最近在對接微信小程序直播相關接口。
在對接【小程序直播】商品管理接口添加和更新商品的時候涉及到
微信上傳臨時素材https://developers.weixin.qq.com/doc/offiaccount/Asset_Management/New_temporary_materials.html接口,於是去看了下這個接口。
由於我是准備做一個微信直播商品的服務,是給其他服務調用的,相當於一個適配器功能。然后就需要別的服務把文件傳給我這個服務,我這個服務再去請求微信的接口。文件傳輸和普通的接口還有些不一樣。
我還是花費了一些時間研究的。這里寫個隨筆,就當給自己做個筆記。
話不多說,直接上代碼:
1、調用微信上傳臨時素材接口方法:
public String formDataPost(String url, MultipartFile file) { BufferedReader reader = null; try { URL urlObj = new URL(url); HttpURLConnection con = (HttpURLConnection) urlObj.openConnection(); con.setRequestMethod("POST"); con.setDoInput(true); con.setDoOutput(true); // post方式不能使用緩存 con.setUseCaches(false); // 設置請求頭信息 con.setRequestProperty("Connection", "Keep-Alive"); con.setRequestProperty("Charset", "UTF-8"); // 設置邊界 String BOUNDARY = "----------" + System.currentTimeMillis(); con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); // 請求正文信息 // 第一部分: StringBuilder sb = new StringBuilder(); // 必須多兩道線 sb.append("--"); sb.append(BOUNDARY); sb.append("\r\n"); sb.append("Content-Disposition: form-data;name=\"file\";filename=\"" + file.getOriginalFilename() + "\"\r\n"); sb.append("Content-Type:application/octet-stream\r\n\r\n"); byte[] head = sb.toString().getBytes("utf-8"); // 獲得輸出流 OutputStream out = new DataOutputStream(con.getOutputStream()); // 輸出表頭 out.write(head); // 文件正文部分 // 把文件已流文件的方式 推入到url中 DataInputStream in = new DataInputStream(file.getInputStream()); int bytes = 0; byte[] bufferOut = new byte[1024]; while ((bytes = in.read(bufferOut)) != -1) { out.write(bufferOut, 0, bytes); } in.close(); // 結尾部分 byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定義最后數據分隔線 out.write(foot); out.flush(); out.close(); StringBuffer buffer = new StringBuffer(); // 定義BufferedReader輸入流來讀取URL的響應 reader = new BufferedReader(new InputStreamReader(con.getInputStream())); String line = null; while ((line = reader.readLine()) != null) { buffer.append(line); } return buffer.toString(); } catch (Exception e) { log.error("發送POST請求出現異常:{}", e); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { log.error("關閉流異常:{}", e); } } } throw new BusinessException(ResultCode.ERROR, new Object[]{"請求微信上傳媒體文件"}); }
2、接收其他服務文件接口
/** * 上傳媒體素材 * <p> * * @return * @throws * @version 1.0.0 * @date 2020/6/4 */ @ApiOperation(value = "上傳媒體素材", httpMethod = "POST") @PostMapping("/upload") public RestResult<UploadMediaResponse> upload(@RequestParam("file") MultipartFile file, @ModelAttribute @Valid @ApiParam(name = "上傳媒體素材請求參數") UploadMediaRequest request) { return success(uploadMediaService.upload(file, request)); }
其中UploadMediaRequest類里面是需要的參數
3、其他服務通過頁面上傳文件然后調用我的上傳媒體素材接口代碼:
/** * 頁面上傳文件接口 * <p> * @return * @throws * @version 1.0.0 * @date 2020/6/6 */ @PostMapping("/upload1") public RestResult upload1(@RequestParam("file") MultipartFile file, @ModelAttribute @Valid @ApiParam(name = "上傳媒體素材請求參數") UploadMediaRequest request) { String url = "http://localhost:8359/xxxx/upload"; HttpHeaders headers = new HttpHeaders(); headers.add("Accept", MediaType.APPLICATION_JSON.toString()); headers.setContentType(MediaType.parseMediaType("multipart/form-data; charset=UTF-8")); MultiValueMap<String, Object> form = new LinkedMultiValueMap(); form.add("fileType", request.getFileType()); form.add("appId", request.getAppId()); try { ByteArrayResource byteArrayResource = this.getByteArrayResource(file.getBytes(), file.getOriginalFilename()); form.add("file", byteArrayResource); HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity(form, headers); ResponseEntity<RestResult> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, RestResult.class, new Object[0]); RestResult body = response.getBody(); return success(body.getData()); } catch (Exception e) { System.out.println(e); } return success(); } private ByteArrayResource getByteArrayResource(byte[] fileBytes, final String originalFilename) throws Exception { ByteArrayResource byteArrayResource = new ByteArrayResource(fileBytes) { public String getFilename() { try { return URLEncoder.encode(originalFilename, "UTF-8"); } catch (Exception e) { return originalFilename; } } }; return byteArrayResource; }
測試結果
參考文章:https://blog.csdn.net/chenzhi7665/article/details/100719047