版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_24138151/article/details/80389403
微信公众号先上传素材,再推送消息java代码实现:
首先公众号的图文消息是可以登录公众号,然后去管理--素材管理 下面去手动添加图文,图片,视频,音乐素材的.这样添加的素材属于永久素材.
用java代码实现的时候,很多人报错无效的media_id, 或无效的thumb_media_id,那是因为你上传的素材是临时的,换成永久id就可以了.
以下是我的几个亲测可用的Test. 具体的需求请参考官方文档 https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1481187827_i0l21
1.获取素材列表
package weixin.tuwen;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import weixin.tuwen.pojo.Material;
import weixin.util.WX_HttpsUtil;
import weixin.util.WX_TokenUtil;
import com.alibaba.fastjson.JSONObject;
import com.qs.util.HttpsPostUtil;
import com.qs.util.httpspost.HttpsUtil;
public class TestGetSucaiList {
/**
* 获取永久素材列表(根据分类)
* 图片(image)、视频(video)、语音 (voice)、图文(news)
* 参数:type offset count
* @throws IOException
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
*/
public static void main(String[] args) throws KeyManagementException, NoSuchAlgorithmException, IOException {
String access_token = WX_TokenUtil.getWXToken().getAccessToken();
String url = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token="+access_token;
//POST请求发送的json参数
Material m = new Material();
m.setType("news");
m.setOffset(0);
m.setCount(10);
JSONObject json = (JSONObject) JSONObject.toJSON(m);
String str = json.toString();
System.out.println(str);
// Map<String,String> createMap = new HashMap<String,String>();
// createMap.put("type","image");
// createMap.put("offset","0");
// createMap.put("count","1");
byte[] result = HttpsUtil.post(url, str, "utf-8");
String strs = new String(result);
System.out.println(strs);
}
}
2.上传音乐素材到公众号 (有需要上传图片的,请自行把参数替换掉)
package weixin.tuwen;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import net.sf.json.JSONObject;
import weixin.util.WX_TokenUtil;
public class UploadSucai {
/**
* @param args
* 上传音乐到公众号
* 请求地址(post):https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token=ACCESS_TOKEN
*/
public static void main(String[] args) {
String access_token = WX_TokenUtil.getWXToken().getAccessToken();
File file = new File("C:/Users/v_yiqqin/Music/asdasd.mp3");
uploadPermanentMedia2(access_token,file,"测试标题","测试描述");
}
/**
* 这里说下,在上传视频素材的时候,微信说不超过20M,我试了下,超过10M调通的可能性都比较小,建议大家上传视频素材的大小小于10M比交好
* @param accessToken
* @param file 上传的文件
* @param title 上传类型为video的参数
* @param introduction 上传类型为video的参数
*/
public static void uploadPermanentMedia2(String accessToken,
File file,String title,String introduction) {
try {
//这块是用来处理如果上传的类型是video的类型的
JSONObject j=new JSONObject();
j.put("title", title);
j.put("introduction", introduction);
// 拼装请求地址
String uploadMediaUrl = "http://api.weixin.qq.com/cgi-bin/material/add_material?access_token=##ACCESS_TOKEN##";
uploadMediaUrl = uploadMediaUrl.replace("##ACCESS_TOKEN##",accessToken);
URL url = new URL(uploadMediaUrl);
String result = null;
long filelength = file.length();
String fileName=file.getName();
String suffix=fileName.substring(fileName.lastIndexOf("."),fileName.length());
String type="voice/mp3"; //我这里写死
/**
* 你们需要在这里根据文件后缀suffix将type的值设置成对应的mime类型的值
*/
HttpURLConnection con = (HttpURLConnection) url.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");
// 设置边界,这里的boundary是http协议里面的分割符,不懂的可惜百度(http 协议 boundary),这里boundary 可以是任意的值(111,2222)都行
String BOUNDARY = "----------" + System.currentTimeMillis();
con.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + BOUNDARY);
// 请求正文信息
// 第一部分:
StringBuilder sb = new StringBuilder();
//这块是post提交type的值也就是文件对应的mime类型值
sb.append("--"); // 必须多两道线 这里说明下,这两个横杠是http协议要求的,用来分隔提交的参数用的,不懂的可以看看http 协议头
sb.append(BOUNDARY);
sb.append("\r\n");
sb.append("Content-Disposition: form-data;name=\"type\" \r\n\r\n"); //这里是参数名,参数名和值之间要用两次
sb.append(type+"\r\n"); //参数的值
//这块是上传video是必须的参数,你们可以在这里根据文件类型做if/else 判断
sb.append("--"); // 必须多两道线
sb.append(BOUNDARY);
sb.append("\r\n");
sb.append("Content-Disposition: form-data;name=\"description\" \r\n\r\n");
sb.append(j.toString()+"\r\n");
/**
* 这里重点说明下,上面两个参数完全可以卸载url地址后面 就想我们平时url地址传参一样,
* http://api.weixin.qq.com/cgi-bin/material/add_material?access_token=##ACCESS_TOKEN##&type=""&description={} 这样,如果写成这样,上面的
* 那两个参数的代码就不用写了,不过media参数能否这样提交我没有试,感兴趣的可以试试
*/
sb.append("--"); // 必须多两道线
sb.append(BOUNDARY);
sb.append("\r\n");
//这里是media参数相关的信息,这里是否能分开下我没有试,感兴趣的可以试试
sb.append("Content-Disposition: form-data;name=\"media\";filename=\""
+ fileName + "\";filelength=\"" + filelength + "\" \r\n");
sb.append("Content-Type:application/octet-stream\r\n\r\n");
System.out.println(sb.toString());
byte[] head = sb.toString().getBytes("utf-8");
// 获得输出流
OutputStream out = new DataOutputStream(con.getOutputStream());
// 输出表头
out.write(head);
// 文件正文部分
// 把文件已流文件的方式 推入到url中
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();
// 结尾部分,这里结尾表示整体的参数的结尾,结尾要用"--"作为结束,这些都是http协议的规定
byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线
out.write(foot);
out.flush();
out.close();
StringBuffer buffer = new StringBuffer();
BufferedReader reader = null;
// 定义BufferedReader输入流来读取URL的响应
reader = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
if (result == null) {
result = buffer.toString();
}
// 使用JSON-lib解析返回结果
JSONObject jsonObject = JSONObject.fromObject(result);
if (jsonObject.has("media_id")) {
System.out.println("media_id:"+jsonObject.getString("media_id"));
} else {
System.out.println(jsonObject.toString());
}
System.out.println("json:"+jsonObject.toString());
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}
}
3.上传临时 或者 永久缩略图素材 (注释掉的地址是临时素材的)
package weixin.tuwen;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import net.sf.json.JSONObject;
import weixin.util.WX_TokenUtil;
public class UploadLinshiSucai {
//临时素材地址
// private static final String UPLOAD_URL = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";
//永久素材的地址
private static final String UPLOAD_URL = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=ACCESS_TOKEN&type=TYPE";
public static String uploadFile(File file, String accessToken, String type) throws Exception{
// File file = new File(filePath);
if(!file.exists() || !file.isFile()) {
throw new IOException("文件不存在!");
}
String url = UPLOAD_URL.replace("ACCESS_TOKEN", accessToken).replace("TYPE", type);
URL urlObj = new URL(url);
//连接
HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
//请求头
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Charset", "UTF-8");
//conn.setRequestProperty("Content-Type","multipart/form-data;");
//设置边界
String BOUNDARY = "----------" + System.currentTimeMillis();
conn.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=\"file\";filename=\""+file.getName()+"\"\r\n");
sb.append("Content-Type:application/octet-stream\r\n\r\n");
byte[] head = sb.toString().getBytes("utf-8");
//输出流
OutputStream out = new DataOutputStream(conn.getOutputStream());
out.write(head);
//文件正文部分
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[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");
out.write(foot);
out.flush();
out.close();
//获取响应
StringBuffer buffer = new StringBuffer();
BufferedReader reader = null;
String result = null;
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = null;
while((line = reader.readLine()) != null) {
buffer.append(line);
}
if(result == null) {
result = buffer.toString();
}
reader.close();
//需要添加json-lib jar包
JSONObject json = JSONObject.fromObject(result);
System.out.println(json);
String mediaId = json.getString("thumb_media_id");
return mediaId;
}
public static void main(String[] args) throws Exception {
String access_token = WX_TokenUtil.getWXToken().getAccessToken();
File file = new File("C:/Users/Music/timg.jpg");
String type = "thumb";
uploadFile(file,access_token,type);
}
}
4.上传图文消息素材
package weixin.tuwen;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import com.alibaba.fastjson.JSONObject;
import com.qs.util.httpspost.HttpsUtil;
import weixin.tuwen.pojo.Tuwen;
import weixin.util.WX_TokenUtil;
/**
* 上传图文消息素材【订阅号与服务号认证后均可用】
* http请求方式: POST
https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token=ACCESS_TOKEN
* @author v_yiqqin
*/
public class TuwenUpload {
public static void main(String[] args) throws KeyManagementException, NoSuchAlgorithmException, IOException{
String access_token = WX_TokenUtil.getWXToken().getAccessToken();
// System.out.println(access_token);
// String url = "https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token="+access_token;
//永久素材地址
String url = "https://api.weixin.qq.com/cgi-bin/material/add_news?access_token="+access_token;
Tuwen tt = new Tuwen();
tt.setThumb_media_id("aprI7dnR4XeWcPEJcjLeIUjcDJv658pne4-2FUzEb6A");
tt.setAuthor("kevin");
tt.setTitle("图文测试66666");
tt.setContent_source_url("www.baidu.com");
tt.setContent("测试内容666666");
tt.setDigest("描述666666");
tt.setShow_cover_pic(1);
JSONObject json = (JSONObject) JSONObject.toJSON(tt);
String str = json.toString();
str = "{"+"\"articles\":["+str+"]"+"}";
byte[] result = HttpsUtil.post(url, str, "utf-8");
String strs = new String(result);
System.out.println(strs);
}
}
5.最后一步,发送图文消息
package weixin.tuwen;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import com.alibaba.fastjson.JSONObject;
import com.qs.util.httpspost.HttpsUtil;
import weixin.tuwen.pojo.GetUserList;
import weixin.tuwen.pojo.Media_id;
import weixin.tuwen.pojo.SendPojo;
import weixin.tuwen.pojo.Text;
import weixin.util.WX_TokenUtil;
public class SendMessage {
/**
* @param args
* @throws IOException
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
*/
public static void main(String[] args) throws KeyManagementException, NoSuchAlgorithmException, IOException {
String access_token = WX_TokenUtil.getWXToken().getAccessToken();
String url = "https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token="+access_token;
//先获取用户openid列表
List userList = GetUserList.getUserList();
String openid = userList.toString();
System.out.println(openid);
Media_id m = new Media_id();
m.setMedia_id("aprI7dnR4XasdsafdghjewetrsdKiawoXw6RFzGM");
JSONObject json1 = (JSONObject) JSONObject.toJSON(m);
String str1 = json1.toString();
System.out.println(str1);
//封装请求参数
SendPojo sp = new SendPojo();
sp.setTouser(userList);
sp.setMpnews(str1);
sp.setMsgtype("mpnews");
sp.setSend_ignore_reprint(0);
// Text t = new Text();
// t.setContent("hello from boxer");
// JSONObject json1 = (JSONObject) JSONObject.toJSON(t);
// String str1 = json1.toString();
// System.out.println(str1);
//
// SendPojo sp = new SendPojo();
// sp.setTouser(userList);
// sp.setMsgtype("text");
// sp.setText(str1);
//
JSONObject json = (JSONObject) JSONObject.toJSON(sp);
String str = json.toString();
str= str.replace("\\", "");
str= str.replace("\"{", "{");
str= str.replace("}\"", "}");
System.out.println(str);
byte[] result = HttpsUtil.post(url, str, "utf-8");
String strs = new String(result);
System.out.println(strs);
}
}
6.获取用户列表(群发用户)
package weixin.tuwen.pojo;
import java.util.List;
import com.alibaba.fastjson.JSONObject;
import weixin.util.WX_HttpsUtil;
import weixin.util.WX_TokenUtil;
public class GetUserList {
/**
* @param args
*/
public static List getUserList() {
String access_token = WX_TokenUtil.getWXToken().getAccessToken();
String url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token="+access_token;
JSONObject result = WX_HttpsUtil.httpsRequest(url, "GET",null);
JSONObject resultJson = new JSONObject(result);
JSONObject data = (JSONObject) resultJson.get("data");
List openidlist = (List) data.get("openid");
return openidlist;
}
}