这是第一次写博客哈,欢迎各种指教评判;
准备:1,,了解Get,Post的方法的本质:get是从指定的资源请求数据,post是 向指定的资源提交要处理的数据。
GET | POST | |
---|---|---|
后退按钮/刷新 | 无害 | 数据会被重新提交(浏览器应该告知用户数据会被重新提交)。 |
书签 | 可收藏为书签 | 不可收藏为书签 |
缓存 | 能被缓存 | 不能缓存 |
编码类型 | application/x-www-form-urlencoded | application/x-www-form-urlencoded 或 multipart/form-data。为二进制数据使用多重编码。 |
历史 | 参数保留在浏览器历史中。 | 参数不会保存在浏览器历史中。 |
对数据长度的限制 | 是的。当发送数据时,GET 方法向 URL 添加数据;URL 的长度是受限制的(URL 的最大长度是 2048 个字符)。 | 无限制。 |
对数据类型的限制 | 只允许 ASCII 字符。 | 没有限制。也允许二进制数据。 |
安全性 | 与 POST 相比,GET 的安全性较差,因为所发送的数据是 URL 的一部分。 在发送密码或其他敏感信息时绝不要使用 GET ! | POST 比 GET 更安全,因为参数不会被保存在浏览器历史或 web 服务器日志中。 |
可见性 | 数据在 URL 中对所有人都是可见的。 | 数据不会显示在 URL 中。 |
2,了解.net模拟浏览器请求:使用.net的内置对象 HttpWebRequest来模拟各种浏览器信息;详情见:点击打开链接
3,了解微信接口流程;
3.1,我们用我们的测试账号或者微信公众号通过Get方法去申请一个Token;
3.2,发送一个穿Json的数据想微信接口发送Post请求,获得一个带有Scene_Id的Tickt;
3.3,将获取的Tickt向微信接口发送获取相应的二维码二进制字符串,浏览器返回的是一串流;
3.4,将流文件保存为图片,或者存为Content-type=“image/jpg”的网页中;
开始写代码吧:
模拟浏览器发送请求获取Token
public string getToken()
{
// 也可以这样写:
string res = "";
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(@"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx94a47c9af96c8fa6&secret=71f7782993d40df716ff8ab369f4ca3a");
//只用修改你的AppID和Secret
req.Method = "GET";
using (WebResponse wr = req.GetResponse())
{
HttpWebResponse myResponse = (HttpWebResponse)req.GetResponse();
StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
string content = reader.ReadToEnd();
JavaScriptSerializer json = new JavaScriptSerializer();
MyJson myACCESSTOKEN = json.Deserialize(content, typeof(MyJson)) as MyJson;
res = myACCESSTOKEN.access_token;
}
return res;
}
发送一个穿Json的数据想微信接口发送Post请求,获得一个带有Scene_Id的Tickt;
public String RequestByPost(int scene_id)//测试的话scene_id 是1到10000之间的一个整数就可以了
{
String token = "";
Cache cache = System.Web.HttpContext.Current.Cache;
if (cache["token"] == null)
{
token = getToken();
DateTime date1 = DateTime.Now;
cache.Insert("token", token, null, DateTime.Now.AddSeconds(7200), TimeSpan.Zero);
}//这是我写的缓存机制,来控制缓存,以为微信的Token生成是有限制的;
string url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + cache["token"];
string postData = "{\"action_name\": \"QR_LIMIT_SCENE\",\"action_info\":{\"scene\":{\"scene_id\":"+scene_id+"}}}";
int num = 1;
String res = "";
string str = null;
while (num-- > 0)
{
try
{
Thread.Sleep((int)(1 * 0x3e8));
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727)";
request.Method = "POST";
request.Accept = "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
request.KeepAlive = true;
request.ContentType = "application/x-www-form-urlencoded";
//request.Proxy = this.webProxy;
HttpRequestCachePolicy policy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
request.CachePolicy = policy;
byte[] bytes = Encoding.GetEncoding("GB2312").GetBytes(postData);
request.ContentLength = bytes.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8, true);
str = reader.ReadToEnd();
response.Close();
reader.Close();
JavaScriptSerializer json = new JavaScriptSerializer();
MyTicket myACCESSTOKEN = json.Deserialize(str, typeof(MyTicket)) as MyTicket;
res = myACCESSTOKEN.ticket;
}
catch (Exception exception)
{
if (exception.Message.IndexOf("内部服务器错误") > 0)
{
return res;
}
continue;
}
}
return res;
}
将获取的Tickt向微信接口发送获取相应的二维码二进制字符串,浏览器返回的是一串流;
public String getPic(int scene_id)
{
string ticket = RequestByPost(scene_id);
string id = Convert.ToString(scene_id);
string url = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + ticket;
string content = string.Empty;
string strpath = string.Empty;
string savepath = string.Empty;
string stUrl = url;
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(stUrl);
req.Method = "GET";
using (WebResponse wr = req.GetResponse())
{
HttpWebResponse myResponse = (HttpWebResponse)req.GetResponse();
strpath = myResponse.ResponseUri.ToString();
WebClient mywebclient = new WebClient();
//savepath = Server.MapPath("\\Content\\wechat") + "\\" + id + ".jpg" ;
// savepath = Server.MapPath("\\Content\\wechat") + "\\" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + (new Random()).Next().ToString().Substring(0, 4) + "." + myResponse.ContentType.Split('/')[1].ToString();
savepath = @"d://tfs/mlms/mlms/content/wechat/original/"+id+".jpg";
try
{
mywebclient.DownloadFile(strpath, savepath);
//保存成自己的文件全路径,newfile就是你上传后保存的文件,
//服务器上的UpLoadFile文件夹必须有读写权限 ;
Image wechat = Image.FromFile(@"d://tfs/mlms/mlms/content/wechat/original/"+id+".jpg");
int smallWidth = 200;
int smallHeight = 200;
//缩略图
Bitmap bitmap = new Bitmap(smallWidth, smallHeight);
Graphics g = Graphics.FromImage(bitmap);
g.DrawImage(wechat, 0, 0, smallWidth, smallHeight);
//保存图片 第二个参数根据自己的图片格式选择
bitmap.Save(@"d://tfs/mlms/mlms/content/wechat/small/"+id+".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
g.Dispose();
bitmap.Dispose();
wechat.Dispose();
}
catch (Exception ex)
{
savepath = ex.ToString();
}
}
return strpath.ToString();
}
你们可以直接复制代码更改Appid和SECRET就可以了,然后调用我的GetPic方法传入一个整数,这样就会在你的电脑的绝对路径下面生成一张二维码;
PS:测试通过的;