文章目录

  • 前言
  • 一、获取上传的临时素材
  • 二、使用步骤
    • 1.引入库以及工具类
    • 2.实现代码
  • 总结

前言

根据之前上传的临时素材会拿到一个media_id,该media_id仅三天内有效
既然有上传,是不是得有获取。接下来就看看获取的方法。


一、获取上传的临时素材

根据media_id拿到企业微信的文件流,后台经过处理,保存服务器或者返回流给前端,前端下载到本地。

二、使用步骤

1.引入库以及工具类

我这里使用了Hutool工具包

<!-- hutool工具包 -->
<dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.4.6</version>
</dependency>

处理文件WeiXinUtil.java的公具类

package com.example.util;import java.io.*;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;import lombok.extern.slf4j.Slf4j;/*** TOO** @author hj* @version 1.0*/
@Slf4j
public class WeiXinUtil {/*** 发送https请求之获取临时素材* @param requestUrl* @param savePath  文件的保存路径,此时还缺一个扩展名* @return* @throws Exception*/public static File getFile(String requestUrl,String savePath,String httpProxyHost,Integer httpProxyPort) throws Exception {// 创建SSLContext对象,并使用我们指定的信任管理器初始化TrustManager[] tm = { new MyX509TrustManager() };SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");sslContext.init(null, tm, new java.security.SecureRandom());// 从上述SSLContext对象中得到SSLSocketFactory对象SSLSocketFactory ssf = sslContext.getSocketFactory();URL url = new URL(requestUrl);//创建代理服务器Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(httpProxyHost, httpProxyPort));//把代理加入请求链接HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection(proxy);httpUrlConn.setSSLSocketFactory(ssf);httpUrlConn.setDoOutput(true);httpUrlConn.setDoInput(true);httpUrlConn.setUseCaches(false);// 设置请求方式(GET/POST)httpUrlConn.setRequestMethod("GET");httpUrlConn.connect();//获取文件扩展名String ext = getExt(httpUrlConn.getContentType());//设置文件名savePath = savePath + System.currentTimeMillis() + ext;log.info("savePath:{}",savePath);//下载文件到f文件File file = new File(savePath);// 获取微信返回的输入流InputStream in = httpUrlConn.getInputStream();//输出流,将微信返回的输入流内容写到文件中FileOutputStream out = new FileOutputStream(file);int length=100*1024;byte[] byteBuffer = new byte[length]; //存储文件内容int byteread =0;int bytesum=0;while (( byteread=in.read(byteBuffer)) != -1) {bytesum += byteread; //字节数 文件大小out.write(byteBuffer,0,byteread);}log.info("bytesum:{}",bytesum);in.close();// 释放资源out.close();in = null;out=null;httpUrlConn.disconnect();return file;}/*** 获取文件扩展名* @param contentType* @return*/private static String getExt(String contentType){if("image/jpeg".equals(contentType)){return ".jpg";}else if("image/png".equals(contentType)){return ".png";}else if("image/gif".equals(contentType)){return ".gif";}return null;}
}

信任管理器

package com.example.util;import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;/*** TOO* 信任管理器* @author hj* @version 1.0*/
public class MyX509TrustManager implements X509TrustManager {@Overridepublic void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {}@Overridepublic void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {}@Overridepublic X509Certificate[] getAcceptedIssuers() {return new X509Certificate[0];}
}

2.实现代码

先了解官方说明:
请求方式:GET(HTTPS)
请求地址:https://qyapi.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID

参数说明 :

参数 必须 说明
access_token 调用接口凭证
media_id 媒体文件id, 见上传临时素材

权限说明:
完全公开,media_id在同一企业内所有应用之间可以共享。

先看接口层代码:controller
我这里是直接返回的文件流,pc端打卡会下载。

package com.example.controller.material;import com.alibaba.fastjson.JSONObject;
import com.example.dto.material.dto.MaterialUploadDTO;
import com.example.dto.material.dto.MediaGetDTO;
import com.example.service.MaterialService;
import com.example.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;/*** TOO* 素材管理* @author hj* @version 1.0*/
@RestController
@RequestMapping("/material/media/api")
@Api(tags = "素材管理")
@Slf4j
public class MaterialManageController {@Autowiredprivate MaterialService materialService;@PostMapping(value = "/mediaGet")@ApiOperation("获取临时素材")public void mediaGet(@RequestBody MediaGetDTO mediaGetDTO,HttpServletRequest request, HttpServletResponse response) throws Exception{File file = materialService.mediaGet(mediaGetDTO);response.setContentType("application/octet-stream");response.setHeader("Content-disposition", "attachment;filename=" + file.getName());response.setHeader("Content-Length", String.valueOf(file.length()));request.setCharacterEncoding("UTF-8");BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());byte[] buff = new byte[2048];int bytesRead;while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {bos.write(buff, 0, bytesRead);}bis.close();bos.close();}
}

服务类:MaterialService

package com.example.service;import com.example.dto.material.dto.MaterialUploadDTO;
import com.example.dto.material.dto.MediaGetDTO;
import com.example.util.Result;
import org.springframework.web.multipart.MultipartFile;import java.io.File;/*** TOO* 素材管理* @author hj* @version 1.0*/
public interface MaterialService {//获取临时素材File mediaGet(MediaGetDTO mediaGetDTO);
}

实现类:MaterialServiceImpl

package com.example.service.impl;import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.example.dto.common.ResponseHead;
import com.example.dto.material.dto.MaterialUploadDTO;
import com.example.dto.material.dto.MediaGetDTO;
import com.example.exception.BusinessException;
import com.example.service.MaterialService;
import com.example.service.TWxAccessTokenService;
import com.example.util.MapUtil;
import com.example.util.Result;
import com.example.util.WeiXinUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;import java.io.File;
import java.util.HashMap;
import java.util.Map;/*** TOO* 素材管理-实现类* @author hj* @version 1.0*/
@Service
@Slf4j
public class MaterialServiceImpl implements MaterialService {@Autowiredprivate TWxAccessTokenService tWxAccessTokenService;@Value("${wechat.material.mediaGet}")private String mediaGet;@Value("${basePath}")private String basePath;@Value("${wechat.corpFlag}")private String corpFlag;@Value("${wechat.cp.httpProxyHost}")private String httpProxyHost;@Value("${wechat.cp.httpProxyPort}")private Integer httpProxyPort;/*** 获取临时素材* @param mediaGetDTO* @return*/@Overridepublic File mediaGet(MediaGetDTO mediaGetDTO) {String accessToken = tWxAccessTokenService.getAccessToken(corpFlag,mediaGetDTO.getRequestHead().getConsumerID());if(StrUtil.isBlank(accessToken)){throw new BusinessException(Result.success(ResponseHead.error("请检查consumerID!")));}String url = mediaGet.replace("ACCESS_TOKEN",accessToken).replace("MEDIA_ID",mediaGetDTO.getRequestBody().getMedia_id());File file;try {file = WeiXinUtil.getFile(url,basePath,httpProxyHost,httpProxyPort);return file;}catch (Exception e){e.printStackTrace();}return null;}
}

其实上面最核心的代码就在WeiXinUtil.getFile(url,basePath,httpProxyHost,httpProxyPort);方法上。
1:url是企业微信的获取地址
2:basePath是传入的服务器地址,不管是本地还是你到时候部署的服务器,都需要提供一个地址用作缓存。可以理解为临时目录。
3:httpProxyHost这是我代理的ip地址,如果不需要代理的可以去掉
4:httpProxyPort代理端口,不需要代理的可以去掉


总结

就是对文件流的一个处理,还有一个信任管理器

SpringBoot实现企业微信-获取临时素材相关推荐

  1. php 获取临时素材,php微信获取临时素材的方法(附代码)

    本篇文章给大家带来的内容是关于php微信获取临时素材的方法(附代码),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助. 注意:1:媒体文件在微信后台保存时间为3天,即3天后media_i ...

  2. 微信获取临时素材接口

    使用到的一种情况: 通过微信接口上传图片并获取到自己的服务器.       首先就是我们需要 用户在公众号上传图片后,该图片要保存在我们自己的数据库里.(比如更换公众号中用户自己的头像)       ...

  3. java微信获取临时素材_获取临时素材文件

    通过media_id获取图片.语音.视频等文件,协议和普通的http文件下载完全相同.该接口即原"下载多媒体文件"接口. 请求说明 Https请求方式: GET 参数说明 参数 必 ...

  4. 微信客服机器人(踩坑记录、SpringBoot、企业微信)

    微信客服机器人(踩坑记录.SpringBoot.企业微信) 转载请注明出处:https://www.jjput.com/archives/wei-xin-ke-fu-ji-qi-ren 总体流程 当有 ...

  5. springboot实现企业微信机器人自动按时播报天气

    springboot实现企业微信机器人自动按时播报天气 第一步搭建项目...这个没有什么好说的 配置: <dependency><groupId>org.apache.http ...

  6. vue从url中获取token并加入到 请求头里_轻流amp;amp;企业微信——获取打卡数据...

    企业微信开放了打卡应用的api,功能包括查询打卡数据,能获取到用户.地点.时间.打卡类型等信息,在轻流中可以基于以上数据做一段时间内的迟到/事假等统计,以及更深层数据处理,方便管理. 第一步:获取ac ...

  7. 企业微信获取corpid,Secret,Agentid

    企业微信获取CORPID,AGENTID,CORPSECRET 在我们对接企业微信时,需要用到以上corpid,Secret 和 Agentid,这些参数的获取方式如下: 1.登录企业微信 https ...

  8. 企业微信获取客户群里用户的unionid;企业微信获取客户详情

    企业微信获取客户群里用户的unionid:企业微信获取客户详情 提示:企业微信获取客户群里用户的unionid其实是通过获取客户详情的接口 文章目录 企业微信获取客户群里用户的unionid:企业微信 ...

  9. Springboot+vue+企业微信登录

    Springboot+ vue +企业微信登录 前端构造企业微信授权链接 第一步,企业微信后台创建一个应用 构造企业微信网页授权OAuth2链接 前后端搭配使用企业微信登录 其他 前端构造企业微信授权 ...

最新文章

  1. 使用fastcoll进行md5碰撞,两个不同的文件md5值一样。
  2. 用CSS实现的模式窗口效果,弹出固定大小的窗口
  3. Python学习5 元组基础知识和常用函数
  4. spring boot中打包插件spring-boot-maven-plugin和maven-jar-plugin的关联
  5. 作者:张国惠(1978-),男,美国新墨西哥大学土木工程系助理教授、博士生导师。...
  6. 我来重新学习 javascript 的面向对象(part 1)
  7. 浏览器的“sleep”
  8. Router_Cloud
  9. viiv个人计算机,欢娱尽情 欢跃平台PC导购
  10. STM32的备份寄存器和控制状态寄存器
  11. Mac M1 百度网盘客户端无法打开,网络连接不上
  12. 数字图像处理 冈萨雷斯 (第四版) 比特平面分层,图像重建
  13. Arduino + USB Host Sheild 实现USB鼠标转PS/2接口
  14. C# 如何添加PPT背景(纯色背景、渐变色背景、图片背景)
  15. ubuntu下使用vscode阅读内核源码或uboot源码使用技巧——search.excludefiles.exclude
  16. Pigeon中的Netty应用
  17. mysql多条语句union_Mysql同时执行多个select语句——union
  18. 面试经历---网易(2016年01月19日下午面试)
  19. UE角色以及角色动画超详细流程干货!这次是step by step!
  20. 【云原生 | 03】裸金属架构之服务器安装VMWare ESXI虚拟化平台详细流程

热门文章

  1. CBLUE-阿里天池中文医疗NLP打榜
  2. OSChina 周二乱弹 —— C 语言是个女的?
  3. WebStorm下载与安装2022版教程注册码WebStorm使用配置
  4. 硬件入门之: 滞回比较器分析计算
  5. Linux ARM平台开发系列讲解(IIO子系统) 2.8.1 IIO驱动开发分析
  6. rabbitmq遇到的一些坑
  7. python列表逆序
  8. 扫描二维码下载app
  9. 静态库与共享库制作,及区别
  10. SaaS公司到底算不算互联网公司?