using Common;
using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.Net;
using System.Text;

     /// <summary>
/// 调用微信接口凭证access_token
/// </summary>
private static string test_access_token
{
get
{
return "XXXXXXXXXXXX";
}
} /// <summary>
/// 新增其他类型永久素材,返回值{"media_id":"eZh1QTjGGSyE-i9k8uHZqrd5LpHfYBsKtUrSfnjf8k0",
/// "url":"http:\/\/mmbiz.qpic.cn\/mmbiz_png\/gHnmqhvpvh5HoibMEcGEAK4eAKvIR18kuKoXbjCiaRa1p1WTBgicYMDvqkjTadib21KUWYpibzfuXj6ibRw8ibw\/0?wx_fmt=png"}
/// </summary>
/// <param name="url">目标地址</param>
/// <param name="path">图片物理文件路径</param>
/// <returns></returns>
public string add_material()
{
//图片(image): 2M,支持bmp/png/jpeg/jpg/gif格式
//语音(voice):2M,播放长度不超过60s,mp3/wma/wav/amr格式
//视频(video):10MB,支持MP4格式
//缩略图(thumb):64KB,支持JPG格式 var file = Request.Files[0];
string fileName = file.FileName;
string url = string.Format("https://api.weixin.qq.com/cgi-bin/material/add_material?access_token={0}&type={1}", test_access_token, "image"); //读取上载文件流
System.IO.Stream fileStream = file.InputStream;
byte[] fileByte = new byte[fileStream.Length];
fileStream.Read(fileByte, 0, fileByte.Length); // 设置参数
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;
}

  

  

     /// <summary>
/// 上传图文消息素材,返回格式:{"type":"news","media_id":"mF1J9boYDAQlYew4wbvbxQKMBkLPa1WzhGbDW7FVak","created_at":1391857799}
/// </summary>
/// <returns></returns>
public string add_news()
{
var news = "{\"articles\":[{\"thumb_media_id\":\"mF1J9boYDAQlYew4wbvbxTgoKle16WjhsxuwhV9ZtQ\",\"author\":\"PDF\",\"title\":\"车行易.违章查询\",\"content_source_url\":\"www.qq.com\",\"content\":\"\",\"digest\":\"为车主朋友们提供优质让人满意的服务\",\"show_cover_pic\":1}]}";
var newsUrl = "https://api.weixin.qq.com/cgi-bin/material/add_news?access_token={0}";
newsUrl = string.Format(newsUrl, test_access_token);
var result = HttpHelper.Post(newsUrl, news, null, "applicaion/json");
WriteLog.WriteLogToFile("add_news RESULT:" + result);
return result;
}

  

     /// <summary>
/// 预览接口(发送给指定的openId)
/// </summary>
/// <returns></returns>
public string preview()
{
//说明:media_id值来自add_news接口返回值中的media_id值
var news = "{\"touser\":\"oTD55jj52uIhOObiwrxCjjrCl9g\",\"mpnews\":{\"media_id\":\"mF1J9boYDAQlYew4wbbxQKMBkLPa1WzwhGbDW7FVak\"},\"msgtype\":\"mpnews\"}";
var newsUrl = "https://api.weixin.qq.com/cgi-bin/message/mass/preview?access_token={0}";
newsUrl = string.Format(newsUrl, test_access_token);
var result = HttpHelper.Post(newsUrl, news, null, "applicaion/json");
WriteLog.WriteLogToFile("preview RESULT:" + result);
return result;
}

  

     /// <summary>
/// 根据标签进行群发【警告,谨慎调用】
/// </summary>
/// <returns></returns>
public string sendall()
{
//说明:media_id值来自add_news接口返回值中的media_id值
var news = "{\"filter\":{\"is_to_all\":false,\"tag_id\":215},\"mpnews\":{\"media_id\":\"mF1J9boYDAQlYew4wbbxQKMBkLPa1WzwhGbDW7FVak\"},\"msgtype\":\"mpnews\",\"send_ignore_reprint\":1,\"clientmsgid\":\"20171107\"}";
var newsUrl = "https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token={0}";
newsUrl = string.Format(newsUrl, test_access_token);
var result = HttpHelper.Post(newsUrl, news, null, "applicaion/json");
WriteLog.WriteLogToFile("sendall RESULT:" + result);
return result;
}

  

     /// <summary>
/// 获取永久素材的列表
/// </summary>
/// <returns></returns>
public string batchget_material()
{
var news = "{\"type\":\"news\",\"offset\":0,\"count\":3}";
var newsUrl = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token={0}";
newsUrl = string.Format(newsUrl, test_access_token);
var result = HttpHelper.Post(newsUrl, news, null, "applicaion/json");
WriteLog.WriteLogToFile("batchget_material RESULT:" + result);
return result;
}

  

     /// <summary>
/// 获取永久素材详细
/// </summary>
/// <returns></returns>
public string get_material()
{
var news = "{\"media_id\":\"mF1J9boYDAQlYew4wbvbxQKMBkLa1WzwhGbDW7FVak\"}";
var newsUrl = "https://api.weixin.qq.com/cgi-bin/material/get_material?access_token={0}";
newsUrl = string.Format(newsUrl, test_access_token);
var result = HttpHelper.Post(newsUrl, news, null, "applicaion/json");
WriteLog.WriteLogToFile("get_material RESULT:" + result);
return result;
}

  

     /// <summary>
/// 获取微信用户分组(用户标记)
/// </summary>
/// <returns></returns>
public string gettags()
{
var newsUrl = "https://api.weixin.qq.com/cgi-bin/tags/get?access_token={0}";
newsUrl = string.Format(newsUrl, test_access_token);
var result = HttpHelper.Get(newsUrl);
WriteLog.WriteLogToFile("tags RESULT:" + result);
return result;
}

  

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web; namespace Common
{
public class HttpHelper
{
/// <summary>
/// 发起GET请求
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
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;
} /// <summary>
/// 获取Post值
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public static string GetPostValue(HttpContext context)
{
System.IO.Stream s = context.Request.InputStream;
int count = 0;
byte[] buffer = new byte[s.Length];
StringBuilder builder = new StringBuilder();
while ((count = s.Read(buffer, 0, buffer.Length)) > 0)
{
builder.Append(Encoding.UTF8.GetString(buffer, 0, count));
}
s.Flush();
s.Close();
return builder.ToString();
}
}
}

  

C# 调用微信接口上传素材和发送图文消息的更多相关文章

  1. java 调用Spring接口上传文件及其他参数填充

    第一步:在Spring配置中添加以下内容 <!-- 配置MultipartResolver 用于文件上传 使用spring的CommosMultipartResolver --> < ...

  2. 调用微信JS上传照片接口上传图片

    public ActionResult UploadImge(string serverId) { var headPath = "/UploadImage/" + DateTim ...

  3. java微信接口之四—上传素材

    一.微信上传素材接口简介 1.请求:该请求是使用post提交地址为: https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token=A ...

  4. 微信上传素材 {"errcode":41005,"errmsg":"media data missing"} 解决方法和思路

    哎lol 连跪两把  就来写写博客    今天遇到一个问题 ,微信公众号开发上传素材是提示报错   41005    errcode":41005,"errmsg":&q ...

  5. Android仿微信图片上传,可以选择多张图片,缩放预览,拍照上传等

    仿照微信,朋友圈分享图片功能 .可以进行图片的多张选择,拍照添加图片,以及进行图片的预览,预览时可以进行缩放,并且可以删除选中状态的图片 .很不错的源码,大家有需要可以下载看看 . 微信 微信 微信 ...

  6. android之使用GridView+仿微信图片上传功能

    由于工作要求最近在使用GridView完成图片的批量上传功能,我的例子当中包含仿微信图片上传.拍照.本地选择.相片裁剪等功能,如果有需要的朋友可以看一下,希望我的实际经验能对您有所帮助. 直接上图,下 ...

  7. C# 调用微信接口的代码

    调用微信接口前需要准备的内容. 1.微信公众平台的appid 2.微信公众平台的secret 3..获取tokenid 4.获取ticket 5.生成签名的随机串 6.生成签名的时间戳 7.生成签名 ...

  8. C# 关于调用微信接口的代码

    调用微信接口前需要准备的内容. 1.微信公众平台的appid 2.微信公众平台的secret 3..获取tokenid 4.获取ticket 5.生成签名的随机串 6.生成签名的时间戳 7.生成签名 ...

  9. 微信图片上传,遇到一个神奇的jgp

    微信图片上传,获取图片base64遇到一个神奇的   jgp var imgFn = function (event) { event.preventDefault(); var id = '#'+$ ...

随机推荐

  1. Android Java中的一些使用例子

    connectivity= ConnectivityService.getInstance(context); ServiceManager.addService(Context.CONNECTIVI ...

  2. recovery 升级过程LED灯闪烁

    Android设备在进入recovery升级的过程,我们在屏幕上面可以看到升级的机器人动画,以及升级的进度显示.这仅限于有屏幕的设备,比如平板PAD,电视TV等,对与没有屏幕的盒子BOX,那么在不接入 ...

  3. C#基础(数据类型运算符)

    ---恢复内容开始--- 1.类 修饰符 class 类名 基类或接口 { } 2.命名规范 成员变量前加_ 首字符小写,后面单词首字母大写(Camel规则) 接口首字母为I 方法的命名使用动词 所有 ...

  4. ccf--20160403---路径解析

    本题思路如下: 具体的细节如下:首先去掉字符串中重复出现的/,然后遇到..,就删除栈的最后一个元素,.忽略 下面是代码和题目: 问题描述 试题编号: 201604-3 试题名称: 路径解析 时间限制: ...

  5. 30个最常用的Linux系统命令行

    1.cd命令这是一个非常基本,也是大家经常需要使用的命令,它用于切换当前目录,它的参数是要切换到的目录的路径,可以是绝对路径,也可以是相对路径.如:cd /root/Docements # 切换到目录 ...

  6. Java设计模式之三 ----- 建造者模式和原型模式

    前言 在上一篇中我们学习了工厂模式,介绍了简单工厂模式.工厂方法和抽象工厂模式.本篇则介绍设计模式中属于创建型模式的建造者模式和原型模式. 建造者模式 简介 建造者模式是属于创建型模式.建造者模式使用 ...

  7. css设置标签居中

    position: absolute;  //相对于已经定位的父元素的位置. left: 50%; top: 50%; transform: translate(-50%,50%);

  8. Jquery+asp.net实现Ajax方式文件下载实例代码

    如果文件中,需要下载一个文件,一般用超级链接的方式即可. 但是如果是图片,浏览器会默认打开图片浏览,不是实现下载. 考虑可以使用jquery ajax提交form请求的方式. jquery downl ...

  9. 控件_RadioGroup&&RadioButton(单选按钮)和Toast

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools=&q ...

  10. sys.argv[]使用

    sys.argv[]说白了就是一个从程序外部获取参数的桥梁,这个"外部"很关键,所以那些试图从代码来说明它作用的解释一直没看明白.因为我们从外部取得的参数可以是多个,所以获得的是一 ...