添加依赖
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
调用微信上传永久多媒体素材接口,获取mediaId
/**
* 上传图片 至公众号媒体素材
* accessToken 接口调用凭证
**/
public static String uploadImage(){
String postUrl = replaceURL("https://api.weixin.qq.com/cgi-bin/material/add_material?access_token={ACCESS_TOKEN}&type={TYPE}", access_token, "image");
File file = new File("C:\\Users\\x1c\\Desktop\\img\\a.jpg");
String mediaId = uploadImage(postUrl, file);
return mediaId;
}
/**
* 图片上传,返回mediaId
*/
public static String uploadImage(String url, File file) {
org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();
PostMethod post = new PostMethod(url);
post.setRequestHeader("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:30.0) Gecko/20100101 Firefox/30.0");
post.setRequestHeader("Host", "file.api.weixin.qq.com");
post.setRequestHeader("Connection", "Keep-Alive");
post.setRequestHeader("Cache-Control", "no-cache");
String result = null;
try{
if (file != null && file.exists()){
FilePart filepart = new FilePart("media", file, "image/jpeg","UTF-8");
Part[] parts = new Part[] {filepart};
MultipartRequestEntity entity = new MultipartRequestEntity(parts, post.getParams());
post.setRequestEntity(entity);
int status = client.executeMethod(post);
if (status == HttpStatus.SC_OK) {
String responseContent = post.getResponseBodyAsString();
// 初始化解析json格式的对象
JsonParser jsonparer = new JsonParser();
JsonObject json = jsonparer.parse(responseContent).getAsJsonObject();
LogUtil.logInfo("uploadImage json =====> " + json.toString());
//"errcode":40004,"errmsg":"invalid media type"}{ // 上传成功 {"type":"TYPE","media_id":"MEDIA_ID","created_at":123456789}
if (json.get("errcode") == null) {
result = json.get("media_id").getAsString();
}
}
}
}catch (Exception e) {
e.printStackTrace();
}finally{
return result;
}
}
根据上一步返回mediaId 推送消息
/**
* 扫码推送/关注推送 消息 点击进入小程序
*
* openid为公众号openid
* mediaId上一步返回
* appid小程序appid,注:需将小程序与公众号绑定在同一个开放平台下
*/
public void sendToApplet(String openId, String mediaId) {
String jsonStr = "{" +
" \"touser\":\""+openId+"\"," +
" \"msgtype\":\"miniprogrampage\"," +
" \"miniprogrampage\":" +
" {" +
" \"title\":\"小程序首页\"," +
" \"appid\":\""+小程序appid+"\"," +
" \"pagepath\":\"pages/index\"," +
" \"thumb_media_id\":\""+mediaId+"\"," +
" }" +
"}";
JSONObject params = JSONObject.parseObject(jsonStr);
JSONObject res = hrefPost("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={ACCESS_TOKEN}", "POST", params.toJSONString(), access_token);
}
工具方法
/**
* 更换url
*/
public static String replaceURL(String url, String... params) {
for (String param : params) {
url = url.replaceFirst("\\{.*?\\}", param);
}
return url;
}
/**
* wx http请求
*/
public static JSONObject hrefPost(String url, String method, String content, String... params) {
try {
URL realUrl = new URL(replaceURL(url, params));
trustAllHttpsCertificates();
HttpURLConnection conn = (HttpURLConnection) realUrl
.openConnection();
// 连接超时
conn.setConnectTimeout(25000);
// 读取超时 --服务器响应比较慢,增大时间
conn.setReadTimeout(25000);
HttpURLConnection.setFollowRedirects(true);
// 请求方式
conn.setRequestMethod(method);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestProperty("User-Agent",
"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0");
conn.connect();
// 获取URLConnection对象对应的输出流
// 发送请求参数
OutputStream os = conn.getOutputStream();
os.write(content.getBytes("UTF-8"));// 传入参数
InputStream is = conn.getInputStream();
int size = is.available();
byte[] jsonBytes = new byte[size];
is.read(jsonBytes);
String result = new String(jsonBytes, "UTF-8");
os.flush();
os.close();
if (conn != null) {
conn.disconnect();
}
return JSONObject.parseObject(result);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}