微信上传素材util
可以自己抽成枚举方法
public class WeChatMaterialUtil {
public static Logger logger = LoggerFactory.getLogger(WeChatMaterialUtil.class);
public static RedisApi redisApi = SpringUtil.getBean(RedisApi.class);
public static WechatConfig wechatConfig = SpringUtil.getBean(WechatConfig.class);
public static EnvConfig envConfig = SpringUtil.getBean(EnvConfig.class);
/**
* 给微信发送素材
* 新增临时素材
*
* @param imageUrl
* @return
* @throws Exception
*/
public static String createFileMaterial(String imageUrl) throws Exception {
String access_token = WechatApi.access_token(redisApi, wechatConfig.getAppid(), wechatConfig.getSecret());
logger.info("access_token--->{}", access_token);
File file = new File(envConfig.getBasepath() + imageUrl);
String typeImage = "image";
String url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=" + access_token + "&type=" + typeImage;
String resp = HttpUtil.httpRequest(url, file);
logger.info("新增临时素材数据--->{}", resp);
return resp;
}
/**
* 给微信发送素材,
* 新增永久素材
*
* @param imageUrl
* @return
* @throws Exception
*/
public static String createEiKyFileMaterial(String imageUrl) throws Exception {
String access_token = WechatApi.access_token(redisApi, wechatConfig.getAppid(), wechatConfig.getSecret());
logger.info("access_token--->{}", access_token);
File file = new File(envConfig.getBasepath() + imageUrl);
String typeImage = "image";
String url = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=" + access_token + "&type=" + typeImage;
String resp = HttpUtil.httpRequest(url, file);
logger.info("新增永久素材数据--->{}", resp);
return resp;
}
/**
* 删除永久素材
*
* @param media_id
* @return
* @throws Exception
*/
public static String deleteEiKyFileMaterial(String media_id) throws Exception {
String access_token = WechatApi.access_token(redisApi, wechatConfig.getAppid(), wechatConfig.getSecret());
String url = "https://api.weixin.qq.com/cgi-bin/material/del_material?access_token=" + access_token;
Map<String, Object> param = new HashMap<>(1);
param.put("media_id", media_id);
String resp = HttpUtil.closeHttpPost(url, JSONObject.toJSONString(param));
logger.info("删除永久素材数据--->{}", resp);
return resp;
}
/**
* 获取永久素材
*
* @param media_id
* @return
* @throws Exception
*/
public static String getEiKyFileMaterial(String media_id) throws Exception {
String access_token = WechatApi.access_token(redisApi, wechatConfig.getAppid(), wechatConfig.getSecret());
String url = "https://api.weixin.qq.com/cgi-bin/material/get_material?access_token=" + access_token;
Map<String, Object> param = new HashMap<>(1);
param.put("media_id", media_id);
String resp = HttpUtil.closeHttpPost(url, JSONObject.toJSONString(param));
logger.info("获取永久素材数据--->{}", resp);
return resp;
}
/**
* @param url 永久素材 : https://api.weixin.qq.com/cgi-bin/material/add_material
* 临时素材 : https://api.weixin.qq.com/cgi-bin/media/upload
* @param type 媒体文件类型,分别有图片(image)、语音(voice)、视频(video)和缩略图(thumb)
* @param imageUrl media 是 form-data中媒体文件标识,有filename、filelength、content-type等信息
* @return
* @throws Exception
*/
public static String createMaterial(String url, String type, String imageUrl) throws Exception {
String access_token = WechatApi.access_token(redisApi, wechatConfig.getAppid(), wechatConfig.getSecret());
logger.info("access_token--->{}", access_token);
File file = new File(envConfig.getBasepath() + imageUrl);
url = url + "?access_token=" + access_token + "&type=" + type;
String resp = HttpUtil.httpRequest(url, file);
logger.info("给微信发送素材数据--->{}", resp);
return resp;
}
}
httpUtil
public class HttpUtil {
public static Logger logger = LoggerFactory.getLogger(HttpUtil.class);
/**
* @param requestUrl 微信上传临时素材的接口url
* @param file 要上传的文件
* @return String 上传成功后,微信服务器返回的消息
* @desc :微信上传素材的请求方法
*/
public static String httpRequest(String requestUrl, File file) {
StringBuffer buffer = new StringBuffer();
try {
//1.建立连接
URL url = new URL(requestUrl);
HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection(); //打开链接
//1.1输入输出设置
httpUrlConn.setDoInput(true);
httpUrlConn.setDoOutput(true);
httpUrlConn.setUseCaches(false); // post方式不能使用缓存
//1.2设置请求头信息
httpUrlConn.setRequestProperty("Connection", "Keep-Alive");
httpUrlConn.setRequestProperty("Charset", "UTF-8");
//1.3设置边界
String BOUNDARY = "----------" + System.currentTimeMillis();
httpUrlConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
// 请求正文信息
// 第一部分:
//2.将文件头输出到微信服务器
StringBuilder sb = new StringBuilder();
sb.append("--"); // 必须多两道线
sb.append(BOUNDARY);
sb.append("\r\n");
sb.append("Content-Disposition: form-data;name=\"media\";filelength=\"" + file.length()
+ "\";filename=\"" + file.getName() + "\"\r\n");
sb.append("Content-Type:application/octet-stream\r\n\r\n");
byte[] head = sb.toString().getBytes("utf-8");
// 获得输出流
OutputStream outputStream = new DataOutputStream(httpUrlConn.getOutputStream());
// 将表头写入输出流中:输出表头
outputStream.write(head);
//3.将文件正文部分输出到微信服务器
// 把文件以流文件的方式 写入到微信服务器中
DataInputStream in = new DataInputStream(new FileInputStream(file));
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
outputStream.write(bufferOut, 0, bytes);
}
in.close();
//4.将结尾部分输出到微信服务器
byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线
outputStream.write(foot);
outputStream.flush();
outputStream.close();
//5.将微信服务器返回的输入流转换成字符串
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 释放资源
inputStream.close();
httpUrlConn.disconnect();
} catch (IOException e) {
System.out.println("发送POST请求出现异常!" + e);
e.printStackTrace();
}
return buffer.toString();
}
public static String sendPostRequest(String url, HttpMethod method, org.springframework.http.HttpEntity<Map<String, Object>> httpEntity) {
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.exchange(url, method, httpEntity, String.class);
return response.getBody();
}
/**
* http请求工具类,post请求
*
* @param url url
* @param param 参数值 仅支持String
* @return
* @throws Exception
*/
public static String closeHttpPost(String url, String param) throws IOException, PassportException {
CloseableHttpClient client = null;
BufferedReader bufferedReader = null;
InputStreamReader inputStreamReader = null;
try {
client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
logger.info("请求域名:{}", url);
httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
if (StringUtils.isNotBlank(param)) {
System.out.println("参数值:" + param);
HttpEntity httpEntity = new StringEntity(param, "utf-8");
httpPost.setEntity(httpEntity);
}
HttpResponse httpResponse = client.execute(httpPost);
if (httpResponse.getStatusLine().getStatusCode() != 200) {
String errorLog = "请求失败,errorCode:" + httpResponse.getStatusLine().getStatusCode();
logger.info(errorLog);
throw new PassportException(url + errorLog);
}
//读取返回信息
String output;
inputStreamReader = new InputStreamReader(httpResponse.getEntity().getContent(), "utf-8");
bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
while ((output = bufferedReader.readLine()) != null) {
stringBuilder.append(output);
}
logger.info("返回值:" + stringBuilder.toString());
return stringBuilder.toString();
} catch (IOException e) {
e.printStackTrace();
throw e;
} finally {
if (client != null) {
client.close();
}
if (bufferedReader != null) {
bufferedReader.close();
}
if (inputStreamReader != null) {
inputStreamReader.close();
}
}
}
}
版权声明:本文为weixin_44343477原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。