C#微信公众号开发之上传永久素材

Http帮助类


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
​
namespace WpfWx
{
    public class HttpHelper
    {
        public static string Get(string url)
        {
            var webReq = (HttpWebRequest)WebRequest.Create(new Uri(url));
​
            webReq.KeepAlive = false;
            webReq.Method = "GET";
            webReq.Timeout = 20000;
            webReq.ProtocolVersion = HttpVersion.Version11;
            webReq.ContentType = "application/x-www-form-urlencoded";
​
            var response = (HttpWebResponse)webReq.GetResponse();
            var readStream = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            Char[] read = new Char[256];
            var count = readStream.Read(read, 0, 256);
            var result = string.Empty;
            while (count > 0)
            {
                result += new String(read, 0, count);
                count = readStream.Read(read, 0, 256);
            }
            response.Close();
            readStream.Close();
            return result;
        }
​
​
        /// <summary>
        ///  POST请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <param name="headers"></param>
        /// <returns></returns>
        public static string Post(string url, string postData, Dictionary<string, string> headers = null, string contentType = null)
        {
            var webReq = (HttpWebRequest)WebRequest.Create(new Uri(url));
​
            Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
            byte[] bytes = encode.GetBytes(postData);
​
            webReq.KeepAlive = false;
            webReq.Method = "POST";
            webReq.Timeout = 20000;
            webReq.ProtocolVersion = HttpVersion.Version11;
            if (contentType == null)
                webReq.ContentType = "application/x-www-form-urlencoded";
            else
                webReq.ContentType = contentType;
​
            webReq.ContentLength = bytes.Length;
            webReq.UserAgent = "Mozilla/5.0";
            if (headers != null)
            {
                foreach (var header in headers)
                    webReq.Headers.Add(header.Key, header.Value);
            }
​
            Stream outStream = webReq.GetRequestStream();
            outStream.Write(bytes, 0, bytes.Length);
            outStream.Close();
​
            var response = (HttpWebResponse)webReq.GetResponse();
            var readStream = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            Char[] read = new Char[256];
            var count = readStream.Read(read, 0, 256);
            var result = string.Empty;
            while (count > 0)
            {
                result += new String(read, 0, count);
                count = readStream.Read(read, 0, 256);
            }
            response.Close();
            readStream.Close();
            return result;
        }
    }
}
​

1、最近更新:永久图片素材新增后,将带有URL返回给开发者,开发者可以在腾讯系域名内使用(腾讯系域名外使用,图片将被屏蔽)。

2、公众号的素材库保存总数量有上限:图文消息素材、图片素材上限为100000,其他类型为1000。

3、素材的格式大小等要求与公众平台官网一致:

图片(image): 2M,支持bmp/png/jpeg/jpg/gif格式

语音(voice):2M,播放长度不超过60s,mp3/wma/wav/amr格式

视频(video):10MB,支持MP4格式

缩略图(thumb):64KB,支持JPG格式

4、图文消息的具体内容中,微信后台将过滤外部的图片链接,图片url需通过"上传图文消息内的图片获取URL"接口上传图片获取。

5、"上传图文消息内的图片获取URL"接口所上传的图片,不占用公众号的素材库中图片数量的100000个的限制,图片仅支持jpg/png格式,大小必须在1MB以下。

6、图文消息支持正文中插入自己帐号和其他公众号已群发文章链接的能力。

新增永久图文素材

接口调用请求说明

http请求方式: POST,https协议 https://api.weixin.qq.com/cgi-bin/material/add_news?access_token=ACCESS_TOKEN

调用示例

{
    "articles": [{
     "title": TITLE,
    "thumb_media_id": THUMB_MEDIA_ID,
    "author": AUTHOR,
    "digest": DIGEST,
    "show_cover_pic": SHOW_COVER_PIC(0 / 1),
    "content": CONTENT,
    "content_source_url": CONTENT_SOURCE_URL,
    "need_open_comment":1,
    "only_fans_can_comment":1
},
    //若新增的是多图文素材,则此处应还有几段articles结构
]
}

参数说明

参数是否必须说明
title标题
thumb_media_id图文消息的封面图片素材id(必须是永久mediaID)
author作者
digest图文消息的摘要,仅有单图文消息才有摘要,多图文此处为空。如果本字段为没有填写,则默认抓取正文前64个字。
show_cover_pic是否显示封面,0为false,即不显示,1为true,即显示
content图文消息的具体内容,支持HTML标签,必须少于2万字符,小于1M,且此处会去除JS,涉及图片url必须来源 "上传图文消息内的图片获取URL"接口获取。外部图片url将被过滤。
content_source_url图文消息的原文地址,即点击“阅读原文”后的URL
need_open_commentUint32 是否打开评论,0不打开,1打开
only_fans_can_commentUint32 是否粉丝才可评论,0所有人可评论,1粉丝才可评论

返回说明

{
   "media_id":MEDIA_ID
}

返回的即为新增的图文消息素材的media_id。

新增永久图文消息

public string add_news()
        {
            var news = "{\"articles\":[{\"thumb_media_id\":\"GSEy95BsrOqFGxoyT-Vu9Ds6M-Rpt6A4XNoQ5BVQhrQ\",\"author\":\"PDF\",\"title\":\"图文消息\",\"content_source_url\":\"www.baidu.com\",\"content\":\"http://mmbiz.qpic.cn/sz_mmbiz_jpg/7aDUwWPgLtRrPX6G7Jsg1I1QP7OuwaSRUGXnO95w5wITjt6FbaDyvMickQXejI5629iaaaH3YPRlbHke8nKicZpQg/0 \",\"digest\":\"图文消息测试摘要\",\"show_cover_pic\":1}]}";
            var newsUrl = "https://api.weixin.qq.com/cgi-bin/material/add_news?access_token={0}";
            newsUrl = string.Format(newsUrl, accessToken);
            var result = HttpHelper.Post(newsUrl, news, null, "applicaion/json");
            return result;
        }
       
 

上传图文消息内的图片获取URL

本接口所上传的图片不占用公众号的素材库中图片数量的100000个的限制。图片仅支持jpg/png格式,大小必须在1MB以下。

接口调用请求说明

http请求方式: POST,https协议 https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=ACCESS_TOKEN 调用示例(使用curl命令,用FORM表单方式上传一个图片): curl -F media=@test.jpg "https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=ACCESS_TOKEN"

参数说明

参数是否必须说明
access_token调用接口凭证
mediaform-data中媒体文件标识,有filename、filelength、content-type等信息

返回说明 正常情况下的返回结果为:

{
    "url":  "http://mmbiz.qpic.cn/mmbiz/gLO17UPS6FS2xsypf378iaNhWacZ1G1UplZYWEYfwvuU6Ont96b1roYs CNFwaRrSaKTPCUdBK9DgEHicsKwWCBRQ/0"
}

其中url就是上传图片的URL,可放置图文消息中使用。

 public string add_pic(string file) 
        {
            string fileName = file;
            string url = string.Format("https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token={0}", accessToken);
            FileStream fs = new FileStream(file, FileMode.OpenOrCreate, FileAccess.Read);
            byte[] fileByte = new byte[fs.Length];
            fs.Read(fileByte, 0, fileByte.Length);
            fs.Close();
            // 设置参数
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            CookieContainer cookieContainer = new CookieContainer();
            request.CookieContainer = cookieContainer;
            request.AllowAutoRedirect = true;
            request.Method = "POST";
            string boundary = DateTime.Now.Ticks.ToString("X"); // 隨機分隔線
            request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;
            byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
            byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
​
            //请求头部信息
            StringBuilder sbHeader =
                new StringBuilder(
                    string.Format(
                        "Content-Disposition:form-data;name=\"media\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n",
                        fileName));
            byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());
​
            Stream postStream = request.GetRequestStream();
            postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
            postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
            postStream.Write(fileByte, 0, fileByte.Length);
            postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
            postStream.Close();
​

            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            Stream instream = response.GetResponseStream();
            StreamReader sr = new StreamReader(instream, Encoding.UTF8);
            string content = sr.ReadToEnd();
            return content;
        }

新增其他类型永久素材

接口调用请求说明

通过POST表单来调用接口,表单id为media,包含需要上传的素材内容,有filename、filelength、content-type等信息。请注意:图片素材将进入公众平台官网素材管理模块中的默认分组。

http请求方式: POST,需使用https https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=ACCESS_TOKEN&type=TYPE 调用示例(使用curl命令,用FORM表单方式新增一个其他类型的永久素材,curl命令的使用请自行查阅资料)

参数说明

参数是否必须说明
access_token调用接口凭证
type媒体文件类型,分别有图片(image)、语音(voice)、视频(video)和缩略图(thumb)
mediaform-data中媒体文件标识,有filename、filelength、content-type等信息

新增永久视频素材需特别注意

在上传视频素材时需要POST另一个表单,id为description,包含素材的描述信息,内容格式为JSON,格式如下:

{
    "title":VIDEO_TITLE,
    "introduction":INTRODUCTION
}

新增永久视频素材的调用示例:

curl "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=ACCESS_TOKEN&type=TYPE" -F media=@media.file -F description='{"title":VIDEO_TITLE, "introduction":INTRODUCTION}'

参数说明

参数是否必须说明
title视频素材的标题
introduction视频素材的描述

返回说明

{
  "media_id":MEDIA_ID,
  "url":URL
}

返回参数说明

参数描述
media_id新增的永久素材的media_id
url新增的图片素材的图片URL(仅新增图片素材时会返回该字段)

错误情况下的返回JSON数据包示例如下(示例为无效媒体类型错误):

{"errcode":40007,"errmsg":"invalid media_id"}

新增图片、视频、声音、缩略图

 public string add_material(string file)
        {
            //(image): 2M,支持bmp/png/jpeg/jpg/gif格式
            //(voice):2M,播放长度不超過60s,mp3/wma/wav/amr格式
            //(video):10MB,支持MP4格式
            //(thumb):64KB,支持JPG格式
​
​
            string fileName = file;
            string url = string.Format("https://api.weixin.qq.com/cgi-bin/material/add_material?access_token={0}&type={1}", accessToken, "image");
            FileStream fs = new FileStream(file, FileMode.OpenOrCreate,FileAccess.Read);
            byte[] fileByte = new byte[fs.Length];
            fs.Read(fileByte, 0, fileByte.Length);
            fs.Close();
            // 設置參數
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            CookieContainer cookieContainer = new CookieContainer();
            request.CookieContainer = cookieContainer;
            request.AllowAutoRedirect = true;
            request.Method = "POST";
            string boundary = DateTime.Now.Ticks.ToString("X"); // 隨機分隔線
            request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;
            byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
            byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");

            StringBuilder sbHeader =
                new StringBuilder(
                    string.Format(
                        "Content-Disposition:form-data;name=\"media\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n",
                        fileName));
            byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());
​
            Stream postStream = request.GetRequestStream();
            postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
            postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
            postStream.Write(fileByte, 0, fileByte.Length);
            postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
            postStream.Close();

            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            Stream instream = response.GetResponseStream();
            StreamReader sr = new StreamReader(instream, Encoding.UTF8);
            string content = sr.ReadToEnd();
            return content;
        }

 

 

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值