代码 如下
/** * 获取小程序 assesstoken * * @param grant_type * @param appid * @param secret * @return */ @POST("/cgi-bin/token") Call<WeChatAssessTokenEntity> getAssessToken(@Query("grant_type") String grant_type, @Query("appid") String appid, @Query("secret") String secret); @POST("/wxa/getwxacodeunlimit") @Streaming Call<ResponseBody> getWeChatImg(@Query("access_token") String access_token, @Body RequestBody route);
调用代码
代码如下
@Override public String saveAndShowImg(String transferId) { WeChatAssessTokenEntity weChatAssessTokenEntity; try { weChatAssessTokenEntity = tencentApi.getAssessToken(WeChatProgramImg.GRANT_TYPE, WeChatProgramImg.APIKEY, WeChatProgramImg.SECRETKEY).execute().body(); if (weChatAssessTokenEntity != null) { //拼装 微信所需要的数据格式 普通的formdata 不可以必须是body Map<String, Object> map = new HashMap<>(); map.put("scene", transferId); map.put("width", 430); map.put("auto_color", true); String json = new Gson().toJson(map);//要传递的json RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), json); //从responsebody中读取图片 Call<ResponseBody> responseBody = tencentApi.getWeChatImg(weChatAssessTokenEntity.getAccess_token(), body); String fileUrl = writeResponseBodyToDisk(responseBody.execute().body()); DeclareTransfer declareTransfer = super.getOne(Condition.getQueryWrapper(new DeclareTransfer(){ @Override public String getTransferId() { return transferId; } })); declareTransfer.setTransferProgramPic(fileUrl); super.saveOrUpdate(declareTransfer); return fileUrl; } } catch (IOException e) { e.printStackTrace(); } return null; }
文件存储代码如下
/** * 根据retrofit 返回的ResponseBoby 取出里买的文件并存在本地 * * @param body * @return */ private String writeResponseBodyToDisk(ResponseBody body) { String fileUrl = ""; try { fileUrl = IdUtil.randomUUID() + ".png"; File futureStudioIconFile = new File("/Users/file/" + fileUrl); InputStream inputStream = null; OutputStream outputStream = null; try { byte[] fileReader = new byte[4096]; inputStream = body.byteStream(); outputStream = new FileOutputStream(futureStudioIconFile); while (true) { int read = inputStream.read(fileReader); if (read == -1) { break; } outputStream.write(fileReader, 0, read); } outputStream.flush(); return fileUrl; } catch (IOException e) { return ""; } finally { if (inputStream != null) { inputStream.close(); } if (outputStream != null) { outputStream.close(); } } } catch (IOException e) { return ""; } }