100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > C#微信公众号开发之上传永久素材

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

时间:2020-03-31 07:58:42

相关推荐

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

Http帮助类

using System;using System.Collections.Generic;using System.IO;using System.Linq;using ;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";elsewebReq.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./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结构]}

参数说明

返回说明

{"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\":\"\",\"content\":\"/sz_mmbiz_jpg/7aDUwWPgLtRrPX6G7Jsg1I1QP7OuwaSRUGXnO95w5wITjt6FbaDyvMickQXejI5629iaaaH3YPRlbHke8nKicZpQg/0 \",\"digest\":\"图文消息测试摘要\",\"show_cover_pic\":1}]}";var newsUrl = "https://api./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./cgi-bin/media/uploadimg?access_token=ACCESS_TOKEN 调用示例(使用curl命令,用FORM表单方式上传一个图片): curl -F media=@test.jpg "https://api./cgi-bin/media/uploadimg?access_token=ACCESS_TOKEN"

参数说明

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

{"url": "/mmbiz/gLO17UPS6FS2xsypf378iaNhWacZ1G1UplZYWEYfwvuU6Ont96b1roYs CNFwaRrSaKTPCUdBK9DgEHicsKwWCBRQ/0"}

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

public string add_pic(string file) {string fileName = file;string url = string.Format("https://api./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./cgi-bin/material/add_material?access_token=ACCESS_TOKEN&type=TYPE 调用示例(使用curl命令,用FORM表单方式新增一个其他类型的永久素材,curl命令的使用请自行查阅资料)

参数说明

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

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

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

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

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

参数说明

返回说明

{"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./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;}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。