现在都流行直播带货,所以我公司作为一家零售行业公司,自然而且也要更上步伐。于是最近在对接微信小程序直播相关接口。
在对接【小程序直播】商品管理接口添加和更新商品的时候涉及到
微信上传临时素材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