最近接收到一个写企业微信临时素材上传工具类的任务,首先开企业微信官方文档的介绍:
文档地址: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.1
Content-Type: multipart/form-data; boundary=-------------------------acebdf13572468
Content-Length: 220
---------------------------acebdf13572468
Content-Disposition: form-data; name="media";filename="wework.txt"; filelength=6
Content-Type: application/octet-stream
mytext
---------------------------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("\r\n");
sb.append("Content-Disposition: form-data;name=\"media\";filename=\"" + fileName + "\"\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(inputStream);
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();
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