知方号

知方号

优雅的实现企业微信临时素材上传<企业微信的文件怎么传到微信上面>

优雅的实现企业微信临时素材上传

最近接收到一个写企业微信临时素材上传工具类的任务,首先开企业微信官方文档的介绍:

文档地址:https://work.weixin.qq.com/api/doc/90000/90135/90253

请求示例:

POST https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=accesstoken001&type=file HTTP/1.1Content-Type: multipart/form-data; boundary=-------------------------acebdf13572468Content-Length: 220---------------------------acebdf13572468Content-Disposition: form-data; name="media";filename="wework.txt"; filelength=6Content-Type: application/octet-streammytext---------------------------acebdf13572468--

上才艺

优雅版本:

/** * * @param fileUrl 网络文件地址, * 图片大小小于2M, * 语音(voice) :2MB, * 播放长度不超过60s,仅支持AMR格式,视频(video) :10MB, * 支持MP4格式,普通文件(file):20MB * @param fileType 图片(image)、语音(voice)、视频(video),普通文件(file) * @return */ public String upload(String fileUrl, QiyeWeixinMediaType fileType){ String result = ""; String accessToken = getAccessToken(); try{ String upUrl = "https://qyapi.weixin.qq.com/cgi-bin/media/upload"; URI uri = UriComponentsBuilder.fromHttpUrl(upUrl) .queryParam("access_token", accessToken) .queryParam("type", fileType.name().toLowerCase()) .build().toUri(); URL mediaUrl = new URL(fileUrl); HttpURLConnection meidaConn = (HttpURLConnection) mediaUrl.openConnection(); meidaConn.setDoOutput(true); meidaConn.setRequestMethod("GET"); InputStream inputStream = meidaConn.getInputStream(); result = new RestTemplate().postForObject(uri, new InputStreamResource(inputStream), String.class); }catch (Exception e){ e.printStackTrace(); } JSONObject jsonObj = JSON.parseObject(result); logger.debug("getMediaId jsonObj: {}", jsonObj); return jsonObj.getString("media_id"); }

啰嗦版本

public String mediaUpload(String fileUrl, QiyeWeixinMediaType fileType){ String result=""; //企业微信 access token的唯一标识符 //token管理器,通过此标识可以找到相应的token(缓存的,或新获取的) String accessToken = accessTokenManager.getToken(new QiyeWeiXinAccessTokenIdentifier(SecretType.externalContact));// String accessToken = getAccessToken(); String upUrl = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token="+accessToken+"&type=" + fileType.name().toLowerCase(); String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1); StringBuffer buffer = new StringBuffer(); BufferedReader reader = null; try { URL mediaUrl = new URL(fileUrl); HttpURLConnection meidaConn = (HttpURLConnection) mediaUrl.openConnection(); meidaConn.setDoOutput(true); meidaConn.setRequestMethod("GET"); InputStream inputStream = meidaConn.getInputStream(); URL urlObj = new URL(upUrl); HttpURLConnection con = (HttpURLConnection) urlObj.openConnection(); con.setRequestMethod("POST"); // 以Post方式提交表单,默认get方式 con.setDoInput(true); con.setDoOutput(true); con.setUseCaches(false); // post方式不能使用缓存 // 设置请求头信息 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(" "); sb.append("Content-Disposition: form-data;name="media";filename="" + fileName + "" "); sb.append("Content-Type:application/octet-stream "); byte[] head = sb.toString().getBytes("utf-8"); // 获得输出流 OutputStream out = new DataOutputStream(con.getOutputStream()); // 输出表头 out.write(head); // 文件正文部分 // 把文件已流文件的方式 推入到url中 DataInputStream in = new DataInputStream(inputStream); int bytes = 0; byte[] bufferOut = new byte[1024]; while ((bytes = in.read(bufferOut)) != -1) { out.write(bufferOut, 0, bytes); } in.close(); // 结尾部分 byte[] foot = (" --" + BOUNDARY + "-- ").getBytes("utf-8");// 定义最后数据分隔线 out.write(foot); out.flush(); out.close(); meidaConn.disconnect(); // 定义BufferedReader输入流来读取URL的响应 InputStream conInputStream = con.getInputStream(); reader = new BufferedReader(new InputStreamReader(conInputStream)); String line = null; while ((line = reader.readLine()) != null) { buffer.append(line); } result = buffer.toString(); } catch (IOException e) { logger.info("发送POST请求出现异常! {}", e); e.printStackTrace(); } finally { try { if (reader != null) { reader.close(); } } catch (IOException e) { e.printStackTrace(); } } JSONObject jsonObj = JSON.parseObject(result); logger.debug("getMediaId jsonObj: {}", jsonObj); return jsonObj.getString("media_id"); }

枚举类

public enum QiyeWeixinMediaType { /** * 图片 */ IMAGE, /** * 语音 */ VOICE, /** * 视频 */ VIDEO, /** * 普通文件 */ FILE;}

才艺表演结束,谢谢大家观看,双击评论666

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至lizi9903@foxmail.com举报,一经查实,本站将立刻删除。

上一篇 没有了

下一篇没有了