前言
一、临时图文链接素材获取
代码如下(示例):
/**
* 根据注册信息,获得的参数,提交get请求,获得accessTkoen
* @author lpe234
* @time 2014-5-21 00:52:15
*/
public String getAccessToken() {
//获取access_token
String preUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
String accessToken = HttpUtil.get(String.format(preUrl, appid, appsecret), null);
Map<String,String> accessTokenMap = JSON.parseObject(accessToken, Map.class);
return accessTokenMap.get("access_token");
}
/**
* 上传图文消息内的图片获取URL 临时图文素材(有效期3天)
*
* @param imgUrl
* @return
*/
public String getUpWxImgUrl(String imgUrl) {
File imgFile = new File(imageUrl);
String access_token = accessTokenUtils.getAccessToken();
String url = "https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=" + access_token;
String jsonStr = formUpload(url, imgFile);
String returnUrl = "";
if (jsonStr.indexOf("errcode") == -1) {
JSONObject jsonObject = JSON.parseObject(jsonStr);
returnUrl = jsonObject.get("url").toString();
}
return returnUrl;
}
/**
* 上传图片
*
* @param urlStr 微信接口路径
* @param file 图片文件
* @return
*/
public static String formUpload(String urlStr, File file) {
String res = "";
HttpURLConnection conn = null;
String BOUNDARY = "---------------------------123821742118716"; // boundary就是request头和上传文件内容的分隔符
try {
URL url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(30000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
OutputStream out = new DataOutputStream(conn.getOutputStream());
// file
String inputName = "";
String filename = file.getName();
String contentType = new MimetypesFileTypeMap().getContentType(file);
if (filename.endsWith(".png")) {
contentType = "image/png";
}
if (contentType == null || contentType.equals("")) {
contentType = "application/octet-stream";
}
StringBuffer strBuf = new StringBuffer();
strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
strBuf.append(
"Content-Disposition: form-data; name=\"" + inputName + "\"; filename=\"" + filename + "\"\r\n");
strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
out.write(strBuf.toString().getBytes());
DataInputStream in = new DataInputStream(new FileInputStream(file));
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
in.close();
byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
out.write(endData);
out.flush();
out.close();
// 读取返回数据
StringBuffer strBuf2 = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
strBuf2.append(line).append("\n");
}
res = strBuf2.toString();
reader.close();
reader = null;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
conn = null;
}
}
return res;
}
二、请求工具类
package com.example.utils.http;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import java.util.Map;
/**
* 客服功能 - 消息发送请求工具类
* Created by Lance on 2020/10/10 17:52
*/
public class HttpUtils {
/**
* Get 发送的请求 用途 根据注册信息,获得的参数,提交get请求,获得accessTkoen
* @param url
* @return
*/
public static String sendGetRequest(String url) {
RestTemplate restTemplate = new RestTemplate();
return restTemplate.getForObject(url, String.class);
}
public static String sendPostRequest(String url, HttpMethod method, HttpEntity<Map<String, Object>> httpEntity) {
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.exchange(url, method, httpEntity, String.class);
return response.getBody();
}
}
总结
返回的是素材id, thumb_url参数直接使用,返回的结果案例:http://mmbiz.qpic.cn/mmbiz_png/oXv914iaE9PC1NSwh0owgtW0OkbfI3gbnsVGfz9Wbt5pv0a8pqqmf4GIYREviaXM5fqLA7JqPVAEE0QibUgC1pZAw/0