08-微信公众号素材管理

08-微信公众号素材管理

目录

1.素材上传

2.素材下载


1.素材上传

首先素材的上传是有一定的规范的,具体的规范请参考微信公众号的官方文档

https://developers.weixin.qq.com/doc/offiaccount/Asset_Management/New_temporary_materials.html

接口调用请求说明

http请求方式:POST/FORM,使用https https://api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE 
调用示例(使用curl命令,用FORM表单方式上传一个多媒体文件):
 curl -F [email protected] "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE"

注:这个请求的调用是Form表单的提交调用,虽然也是Post调用,但是需要单独的进行处理。

首先写文件上传的信息:

文件上传的流程是这样的。

创建链接(长链接) -> 上传文件(文件分为头部信息、文件本身的信息、尾部信息)->通过连接获取微信服务器返回的信息。

/基础信息处理(这块根据自己的情况定)
String url= "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";
String ACCESS_TOKEN ="42_dKlAQhM_ZDheqRj0CfT1t8iItzigdNezTAqB9oWNDsThoGJy5ZqnR7_jyssyFAaI6Qy6xNpI1-ZoKoRhQfmp9uAZyieNJ0IV2tkUZlAjmI21_pM7MFSIWRt2w2095zu-rM2eNAt6_NLtY6egYXPcADAUTL";
String path = "G:\\1.jpg";
String type= "image";
File file = new File(path);
url = url.replace("ACCESS_TOKEN",ACCESS_TOKEN).replace("TYPE",type);
//创建链接(组装连接信息等)
URL url1 = new URL(url);
// 因为调用的是HTTP的请求所以这块需要进行类型转换下
HttpsURLConnection conn = (HttpsURLConnection) url1.openConnection();
//设置连接的信息
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
//设置请求头信息
conn.setRequestProperty("Connection","Keep-Alive");
conn.setRequestProperty("Charset","utf8");
//设置数据边界
String boundary = "-------"+System.currentTimeMillis();
conn.setRequestProperty("Content-Type","multipart/form-data;boundary"+boundary);

// 组装数据信息-----------------------------------------------------------------------
 //获取输出流
 OutputStream out = conn.getOutputStream();
 //创建输入流
 InputStream in = new FileInputStream(file);
 //准备数据
 StringBuilder sb = new StringBuilder();
 sb.append("--");
 sb.append(boundary);
 sb.append("\r\n");
 sb.append("Content-Disposition:form-data;name=\"media\";filename=\""+file.getName()+"\"\r\n");
 sb.append("Content-Type:application/octet-stream\r\n\r\n");
 out.write(sb.toString().getBytes());
 //写文件的内容
 byte [] b = new byte[1024];
 int leng;
 while ((leng = in.read(b))!=-1){
//    System.out.println(new String(b,0,leng));
//    out.write(new String(b,0,leng).getBytes("utf8"));
      out.write(b,0,leng);
  }
  //写尾部信息
  String foot = "\r\n--"+boundary+"--\r\n";
  out.write(foot.getBytes());
  out.flush();
  out.close();
//获取连接返回的信息  
//读取数据
InputStream inputStream = conn.getInputStream();
StringBuilder sb1 = new StringBuilder();
while ((leng = inputStream.read(b))!=-1){
    sb1.append(new String(b,0,leng));
}
System.out.println(sb1.toString());

测试结果如下:

2.素材下载

素材下载的功能就不写了,主要就是通过如下请求调用获取文件。

接口调用请求说明

http请求方式: GET,https调用 https://api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID 
请求示例(示例为通过curl命令获取多媒体文件) 
curl -I -G "https://api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID"

把ACCESS_TOKEN和MEDIA_ID数据进行替换直接在浏览器访问,就可以下载对应的上传的图片。

猜你喜欢

转载自blog.csdn.net/baidu_31572291/article/details/114338949