Java微信公众平台之素材管理

2025-05-29 0 56

微信素材管理和群发这块文档对java很不友好。本文只对新增临时素材,新增永久素材做介绍,其余获取、删除、修改自行补充

公众号经常有需要用到一些临时性的多媒体素材的场景,例如在使用接口特别是发送消息时,对多媒体文件、多媒体消息的获取和调用等操作,是通过media_id来进行的。素材管理接口对所有认证的订阅号和服务号开放

素材的限制

图片(image): 2m,支持png\\jpeg\\jpg\\gif格式
语音(voice):2m,播放长度不超过60s,支持amr\\mp3格式
视频(video):10mb,支持mp4格式
缩略图(thumb):64kb,支持jpg格式

一、新增临时素材

接口:https://api.weixin.qq.com/cgi-bin/media/upload?access_token=access_token&type=type,再传一个媒体文件类型,可以是图片(image)、语音(voice)、视频(video)和缩略图(thumb)。

1、订阅号和服务号要通过认证
2、临时素材media_id是可复用的

3、媒体文件在微信后台保存时间为3天,即3天后media_id失效。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50
/**

* 上传临时素材(本地)

*

* @param accesstoken

* @param type

* 媒体文件类型,分别有图片(image)、语音(voice)、视频(video)和缩略图(thumb)

* @param path

* 图片路径

* @return

*/

public static uploadmediasresult uploadtempmediafile(string accesstoken, string type, string path) {

uploadmediasresult result = null;

treemap<string, string> params = new treemap<>();

params.put("access_token", accesstoken);

params.put("type", type);

try {

string json = httpsuploadmediafile(systemconfig.post_method, wechatconfig.upload_temp_media_type_url,

params, path);

result = jsonutil.fromjsonstring(json, uploadmediasresult.class);

} catch (exception e) {

e.printstacktrace();

}

return result;

}

/**

* 上传临时素材(网络)

*

* @param accesstoken

* @param type

* 媒体文件类型,分别有图片(image)、语音(voice)、视频(video)和缩略图(thumb)

* @param path

* 图片路径

* @return

*/

public static uploadmediasresult uploadtempmedia(string accesstoken, string type, string path) {

uploadmediasresult result = null;

treemap<string, string> params = new treemap<>();

params.put("access_token", accesstoken);

params.put("type", type);

try {

string json = httpsuploadmedia(systemconfig.post_method, wechatconfig.upload_temp_media_type_url, params,

path, 0, 0);

result = jsonutil.fromjsonstring(json, uploadmediasresult.class);

} catch (exception e) {

e.printstacktrace();

}

return result;

}

二、新增永久素材

接口:https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=access_token&type=type,媒体文件类型,分别有图片(image)、语音(voice)、视频(video,例外)和缩略图(thumb)

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45
/**

* 上传永久素材(本地)

*

* @param accesstoken

* @param type

* 媒体文件类型,分别有图片(image)、语音(voice)、视频(video)和缩略图(thumb)

* @return

*/

public static uploadmediasresult uploadforevermediafile(string accesstoken, string type, string path) {

uploadmediasresult result = null;

treemap<string, string> params = new treemap<>();

params.put("access_token", accesstoken);

params.put("type", type);

try {

string json = httpsuploadmediafile(systemconfig.post_method, wechatconfig.upload_forever_media_type_url,

params, path);

result = jsonutil.fromjsonstring(json, uploadmediasresult.class);

} catch (exception e) {

e.printstacktrace();

}

return result;

}

/**

* 上传永久素材(网络)

*

* @param accesstoken

* @param type

* 媒体文件类型,分别有图片(image)、语音(voice)、视频(video)和缩略图(thumb)

* @return

*/

public static uploadmediasresult uploadforevermedia(string accesstoken, string type, string path) {

uploadmediasresult result = null;

treemap<string, string> params = new treemap<>();

params.put("access_token", accesstoken);

params.put("type", type);

try {

string json = httpsuploadmedia(systemconfig.post_method, wechatconfig.upload_forever_media_type_url, params,

path, 0, 0);

result = jsonutil.fromjsonstring(json, uploadmediasresult.class);

} catch (exception e) {

e.printstacktrace();

}

return result;

}

新增永久视频素材需特别注意,在上传视频素材时需要post另一个表单,id为description,包含素材的描述信息title和introduction,内容格式为json

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41
/**

* 上传永久素材(video)

*

* @param accesstoken

* @return

*/

public static string uploadforevermediafile(string accesstoken, string title, string introduction, string path) {

treemap<string, string> params = new treemap<>();

params.put("access_token", accesstoken);

params.put("type", "video");

string mediaid = null;

try {

string json = httpsuploadvideomediafile(systemconfig.post_method,

wechatconfig.upload_forever_media_type_url, params, path, title, introduction);

mediaid = jsonutil.fromjsonstring(json, "media_id");

} catch (exception e) {

e.printstacktrace();

}

return mediaid;

}

/**

* 上传永久素材(video,网络)

*

* @param accesstoken

* @return

*/

public static string uploadforevermedia(string accesstoken, string title, string introduction, string path) {

treemap<string, string> params = new treemap<>();

params.put("access_token", accesstoken);

params.put("type", "video");

string mediaid = null;

try {

string json = httpsuploadvideomedia(systemconfig.post_method, wechatconfig.upload_forever_media_type_url,

params, path, title, introduction, 0, 0);

mediaid = jsonutil.fromjsonstring(json, "media_id");

} catch (exception e) {

e.printstacktrace();

}

return mediaid;

}

三、新增永久图文素材

接口:https://api.weixin.qq.com/cgi-bin/material/add_news?access_token=access_token,post信息参见uploadnewsmedia 实体类

对于常用的素材,开发者可通过本接口上传到微信服务器,永久使用.

1、永久图片素材新增后,将带有url返回给开发者,开发者可以在腾讯系域名内使用(腾讯系域名外使用,图片将被屏蔽)。
2、公众号的素材库保存总数量有上限:图文消息素材、图片素材上限为5000,其他类型为1000。
3、图文消息的具体内容中,微信后台将过滤外部的图片链接,图片url需通过"上传图文消息内的图片获取url"接口上传图片获取。
4、"上传图文消息内的图片获取url"接口所上传的图片,不占用公众号的素材库中图片数量的5000个的限制,图片仅支持jpg/png格式,大小必须在1mb以下。
5、图文消息支持正文中插入自己帐号和其他公众号已群发文章链接的能力。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22
/**

* 上传永久图文消息的素材

*

* @param accesstoken

* 授权token

* @param entity

* 图文消息对象

* @return

*/

public static uploadmediasresult uploadnewsmedia(string accesstoken, list<uploadnewsmedia> entity) {

uploadmediasresult result = null;

treemap<string, string> params = new treemap<>();

params.put("access_token", accesstoken);

// post 提交的参数

treemap<string, list<uploadnewsmedia>> dataparams = new treemap<string, list<uploadnewsmedia>>();

dataparams.put("articles", entity);

string data = jsonutil.tojsonstring(dataparams);

string json = httprequtil.httpsdefaultexecute(systemconfig.post_method,

wechatconfig.upload_forever_news_media_url, params, data);

result = jsonutil.fromjsonstring(json, uploadmediasresult.class);

return result;

}

四、上传图文消息内的图片获取url

接口:https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=access_token

本接口所上传的图片不占用公众号的素材库中图片数量的5000个的限制。图片仅支持jpg/png格式,大小必须在1mb以下,此接口返回的url就是上传图片的url,可放置图文消息中使用。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41
/**

* 上传图文消息内的图片获取url(本地)

*

* @param accesstoken

* @param path

* @return

*/

public static string uploadimgmediafile(string accesstoken, string path) {

treemap<string, string> params = new treemap<>();

params.put("access_token", accesstoken);

string url = null;

try {

string json = httpsuploadmediafile(systemconfig.post_method, wechatconfig.upload_img_media_url, params,

path);

url = jsonutil.fromjsonstring(json, "url");

} catch (exception e) {

e.printstacktrace();

}

return url;

}

/**

* 上传图文消息内的图片获取url(网络)

*

* @param accesstoken

* @param path

* @return

*/

public static string uploadimgmedia(string accesstoken, string path) {

treemap<string, string> params = new treemap<string, string>();

params.put("access_token", accesstoken);

string url = null;

try {

string json = httpsuploadmedia(systemconfig.post_method, wechatconfig.upload_img_media_url, params, path, 0,

0);

url = jsonutil.fromjsonstring(json, "url");

} catch (exception e) {

e.printstacktrace();

}

return url;

}

五、部分工具类

配置类

?

1

2

3

4
public static final string upload_img_media_url = "https://api.weixin.qq.com/cgi-bin/media/uploadimg";

public static final string upload_forever_news_media_url = "https://api.weixin.qq.com/cgi-bin/material/add_news";

public static final string upload_temp_media_type_url = "https://api.weixin.qq.com/cgi-bin/media/upload";

public static final string upload_forever_media_type_url = "https://api.weixin.qq.com/cgi-bin/material/add_material";

上传图文消息素材返回类

?

1

2

3

4

5

6

7

8

9

10

11

12

13
package com.phil.wechat.msg.model.media;

/**

* 上传图文消息素材返回的结果

* @author phil

* @date 2017年9月20日

*

*/

public class uploadmediasresult {

private string type; // 媒体文件类型,分别有图片(image)、语音(voice)、视频(video)和缩略图(thumb),次数为news,即图文消息

private string media_id; // 媒体文件/图文消息上传后获取的唯一标识

private string created_at; // 媒体文件上传时间

}

上传图文消息素材实体类

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20
package com.phil.wechat.msg.model.media;

import java.io.serializable;

/**

* 上传图文消息素材实体类

* @author phil

* @date 2017年9月20日

*/

public class uploadnewsmedia implements serializable {

private static final long serialversionuid = 6551817058101753854l;

private string thumb_media_id; // 图文消息缩略图的media_id,可以在基础支持-上传多媒体文件接口中获得

private string author; // 图文消息的作者

private string title; // 图文消息的标题

private string content_source_url; // 图文消息点击阅读原文的链接

private string content; // 图文消息页面的内容,支持html标签

private string digest; // 图文消息的描述

private int show_conver_pic; // 是否显示为封面 1表示显示为封面 0 不显示为封面

}

上传方法

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280
/**

* 上传媒体文件(本地)

*

* @param method

* 请求方法 get/post

* @param path

* api的路径

* @param param

* api参数

* @param mediapath

* 待上传的image/music 的path

* @return

* @throws exception

*/

public static string httpsuploadmediafile(string method, string path, map<string, string> param, string mediapath)

throws exception {

string result = null;

url url = new url(setparmas(param, path, ""));

outputstream output = null;

datainputstream inputstream = null;

try {

file file = new file(mediapath);

if (!file.isfile() || !file.exists()) {

throw new ioexception("file is not exist");

}

httpurlconnection con = (httpurlconnection) url.openconnection();

con.setdoinput(true);

con.setdooutput(true);

con.setusecaches(false);

con.setrequestmethod(systemconfig.post_method);

// 设置请求头信息

con.setrequestproperty("connection", "keep-alive");

con.setrequestproperty("charset", systemconfig.default_character_encoding);

// 设置边界

string boundary = "----------" + system.currenttimemillis();

con.setrequestproperty("content-type", "multipart/form-data; boundary=" + boundary);

// 请求正文信息

// 第一部分

output = new dataoutputstream(con.getoutputstream());

ioutils.write(("--" + boundary + "\\r\\n").getbytes(systemconfig.default_character_encoding), output);

ioutils.write(("content-disposition: form-data;name=\\"media\\"; filename=\\"" + file.getname() + "\\"\\r\\n")

.getbytes(systemconfig.default_character_encoding), output);

ioutils.write(

"content-type:application/octet-stream\\r\\n\\r\\n".getbytes(systemconfig.default_character_encoding),

output);

// ioutils.write(("content-type: "+ fileext + "\\r\\n\\r\\n").getbytes(), output);

// 文件正文部分

// 把文件已流文件的方式 推入到url中

inputstream = new datainputstream(new fileinputstream(file));

ioutils.copy(inputstream, output);

// 结尾部分

ioutils.write(("\\r\\n--" + boundary + "--\\r\\n").getbytes(systemconfig.default_character_encoding), output);

output.flush();

result = inputstreamtostring(con.getinputstream());

} catch (malformedurlexception e) {

e.printstacktrace();

} catch (protocolexception e) {

e.printstacktrace();

} catch (ioexception e) {

throw new ioexception("read data error");

} finally {

ioutils.closequietly(output);

ioutils.closequietly(inputstream);

}

return result;

}

/**

* 上传媒体文件(不能本地)

*

* @param method

* 请求方法 get/post

* @param path

* api的路径

* @param param

* api参数

* @param mediapath

* 待上传的image/music 的path

* @param conntime

* 连接时间 默认为5000

* @param readtime

* 读取时间 默认为5000

* @return

* @throws exception

*/

public static string httpsuploadmedia(string method, string path, map<string, string> param, string mediapath,

int conntime, int readtime) throws exception {

string result = "";

url url = new url(setparmas(param, path, ""));

outputstream output = null;

bufferedinputstream inputstream = null;

try {

string boundary = "----";

httpurlconnection conn = getconnection(method, url);

conn.setconnecttimeout(conntime == 0 ? default_conntime : conntime);

conn.setreadtimeout(readtime == 0 ? default_upload_readtime : readtime);

conn.setrequestproperty("content-type", "multipart/form-data;boundary=" + boundary);

output = conn.getoutputstream();

url mediaurl = new url(mediapath);

if (mediaurl != null) {

httpurlconnection mediaconn = (httpurlconnection) mediaurl.openconnection();

mediaconn.setdooutput(true);

mediaconn.setusecaches(false);

mediaconn.setrequestmethod(systemconfig.get_method);

mediaconn.setconnecttimeout(conntime == 0 ? default_conntime : conntime);

mediaconn.setreadtimeout(readtime == 0 ? default_upload_readtime : readtime);

string conntype = mediaconn.getcontenttype();

// 获得文件扩展

string fileext = getfileext(conntype);

ioutils.write(("--" + boundary + "\\r\\n").getbytes(), output);

ioutils.write(("content-disposition: form-data; name=\\"media\\"; filename=\\"" + getfilename(mediapath)

+ "\\"\\r\\n").getbytes(), output);

ioutils.write(("content-type: " + fileext + "\\r\\n\\r\\n").getbytes(), output);

inputstream = new bufferedinputstream(mediaconn.getinputstream());

ioutils.copy(inputstream, output);

ioutils.write(("\\r\\n----" + boundary + "--\\r\\n").getbytes(), output);

mediaconn.disconnect();

// 获取输入流

result = inputstreamtostring(conn.getinputstream());

}

} catch (malformedurlexception e) {

e.printstacktrace();

} catch (protocolexception e) {

e.printstacktrace();

} catch (ioexception e) {

e.printstacktrace();

} finally {

ioutils.closequietly(output);

ioutils.closequietly(inputstream);

}

return result;

}

/**

* 上传video媒体文件(本地)

*

* @param method

* 请求方法 get/post

* @param path

* api的路径

* @param param

* api参数

* @param mediapath

* 待上传的voide 的path

* @param title

* 视频标题

* @param introduction

* 视频描述

* @return

* @throws exception

*/

public static string httpsuploadvideomediafile(string method, string path, map<string, string> param,

string mediapath, string title, string introduction) throws exception {

string result = null;

url url = new url(setparmas(param, path, ""));

outputstream output = null;

datainputstream inputstream = null;

try {

file file = new file(mediapath);

if (!file.isfile() || !file.exists()) {

throw new ioexception("file is not exist");

}

httpurlconnection con = (httpurlconnection) url.openconnection();

con.setdoinput(true);

con.setdooutput(true);

con.setusecaches(false);

con.setrequestmethod(systemconfig.post_method);

// 设置请求头信息

con.setrequestproperty("connection", "keep-alive");

con.setrequestproperty("charset", systemconfig.default_character_encoding);

// 设置边界

string boundary = "----------" + system.currenttimemillis();

con.setrequestproperty("content-type", "multipart/form-data; boundary=" + boundary);

// 请求正文信息

// 第一部分

output = new dataoutputstream(con.getoutputstream());

ioutils.write(("--" + boundary + "\\r\\n").getbytes(systemconfig.default_character_encoding), output);

ioutils.write(("content-disposition: form-data;name=\\"media\\"; filename=\\"" + file.getname() + "\\"\\r\\n")

.getbytes(), output);

ioutils.write("content-type: video/mp4 \\r\\n\\r\\n".getbytes(), output);

// 文件正文部分

// 把文件已流文件的方式 推入到url中

inputstream = new datainputstream(new fileinputstream(file));

ioutils.copy(inputstream, output);

// 结尾部分

ioutils.write(("--" + boundary + "\\r\\n").getbytes(systemconfig.default_character_encoding), output);

ioutils.write("content-disposition: form-data; name=\\"description\\";\\r\\n\\r\\n"

.getbytes(systemconfig.default_character_encoding), output);

ioutils.write(("{\\"title\\":\\"" + title + "\\",\\"introduction\\":\\"" + introduction + "\\"}")

.getbytes(systemconfig.default_character_encoding), output);

ioutils.write(("\\r\\n--" + boundary + "--\\r\\n\\r\\n").getbytes(systemconfig.default_character_encoding),

output);

output.flush();

result = inputstreamtostring(con.getinputstream());

} catch (malformedurlexception e) {

e.printstacktrace();

} catch (protocolexception e) {

e.printstacktrace();

} catch (ioexception e) {

throw new ioexception("read data error");

} finally {

ioutils.closequietly(output);

ioutils.closequietly(inputstream);

}

return result;

}

/**

* 上传video媒体文件(网络)

*

* @param method

* 请求方法 get/post

* @param path

* api的路径

* @param param

* api参数

* @param mediapath

* 待上传的voide 的path

* @param title

* 视频标题

* @param introduction

* 视频描述

* @param conntime

* 连接时间 默认为5000

* @param readtime

* 读取时间 默认为5000

* @return

* @throws exception

*/

public static string httpsuploadvideomedia(string method, string path, map<string, string> param, string mediapath,

string title, string introduction, int conntime, int readtime) throws exception {

string result = null;

url url = new url(setparmas(param, path, ""));

outputstream output = null;

bufferedinputstream inputstream = null;

try {

string boundary = "----";

httpurlconnection conn = getconnection(method, url);

conn.setconnecttimeout(conntime == 0 ? default_conntime : conntime);

conn.setreadtimeout(readtime == 0 ? default_upload_readtime : readtime);

conn.setrequestproperty("content-type", "multipart/form-data;boundary=" + boundary);

output = conn.getoutputstream();

url mediaurl = new url(mediapath);

if (mediaurl != null) {

httpurlconnection mediaconn = (httpurlconnection) mediaurl.openconnection();

mediaconn.setdooutput(true);

mediaconn.setusecaches(false);

mediaconn.setrequestmethod(systemconfig.get_method);

mediaconn.setconnecttimeout(conntime == 0 ? default_conntime : conntime);

mediaconn.setreadtimeout(readtime == 0 ? default_upload_readtime : readtime);

ioutils.write(("--" + boundary + "\\r\\n").getbytes(), output);

ioutils.write(("content-disposition: form-data; name=\\"media\\"; filename=\\"" + getfilename(mediapath)

+ "\\"\\r\\n").getbytes(), output);

ioutils.write("content-type: video/mp4 \\r\\n\\r\\n".getbytes(), output);

inputstream = new bufferedinputstream(mediaconn.getinputstream());

ioutils.copy(inputstream, output);

// 结尾部分

ioutils.write(("--" + boundary + "\\r\\n").getbytes(systemconfig.default_character_encoding), output);

ioutils.write("content-disposition: form-data; name=\\"description\\";\\r\\n\\r\\n"

.getbytes(systemconfig.default_character_encoding), output);

ioutils.write(("{\\"title\\":\\"" + title + "\\",\\"introduction\\":\\"" + introduction + "\\"}")

.getbytes(systemconfig.default_character_encoding), output);

ioutils.write(("\\r\\n--" + boundary + "--\\r\\n\\r\\n").getbytes(systemconfig.default_character_encoding),

output);

mediaconn.disconnect();

// 获取输入流

result = inputstreamtostring(conn.getinputstream());

}

} catch (malformedurlexception e) {

e.printstacktrace();

} catch (protocolexception e) {

e.printstacktrace();

} catch (ioexception e) {

throw new ioexception("read data error");

} finally {

ioutils.closequietly(output);

ioutils.closequietly(inputstream);

}

return result;

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持快网idc。

原文链接:https://blog.csdn.net/phil_jing/article/details/78755782

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 Java微信公众平台之素材管理 https://www.kuaiidc.com/111716.html

相关文章

发表评论
暂无评论