HttpClient是微软提供的Http操作的类库。在.Net下创建项目后需要引入System.Net.Http,然后using System.Net.Http。微信Web获得登录二维码用的是Http的get方法。在HttpClient中是通过GetAsync进行。其中还包括获取当前时间的毫秒数,通过正则表达式获取uuid,并把获得的微信登录二维码保存到本地png文件中。具体如下:
Stringuuid = "";
//创建HttpClient实例
HttpClient httpClient = new HttpClient();
//以下代码是获得当前时间至1970年1月1号的毫秒数
long currentTicks=DateTime.Now.Ticks;
DateTime dtFrom = new DateTime(1970, 1, 1, 0, 0, 0, 0);
long currentMillis = (currentTicks - dtFrom.Ticks) / 10000;
//获取微信Web的uuid
HttpResponseMessage response = httpClient.GetAsync("https://login.weixin.qq.com/jslogin?appid=wx782c26e4c19acffb&redirect_uri=https%3A%2F%2Fwx.qq.com%2Fcgi-bin%2Fmmwebwx-bin%2Fwebwxnewloginpage&fun=new&lang=zh_CN&_=";+ currentMillis.ToString()).Result;
//判断是否成功
if (response.IsSuccessStatusCode)
{
String result = response.Content.ReadAsStringAsync().Result;
//通过正则表达式获取uuid
String ss="window.QRLogin.code = (\\d+); window.QRLogin.uuid = \"(\\S+?)\";";
Regex regex =new Regex(ss);
Match match = regex.Match(result);
uuid=match.Groups[2].Value;
//获取uuid后,通过uuid获得登录二维码,这里返回的png字节流
response=httpClient.GetAsync("https://login.weixin.qq.com/qrcode/";+ uuid).Result;
byte[] bytes = response.Content.ReadAsByteArrayAsync().Result;// .ReadAsStreamAsync().Result;
//在本地创建png文件,把返回的二维码图片保存在png文件中
FileStream pngFile = new FileStream("d:\\anxiuyun\\login\\kk.png",FileMode.Create);
pngFile.Write(bytes,0,bytes.Length);
pngFile.Flush();
pngFile.Close();
}
这里获得微信web登录二维码用了微信的两个接口:
1、get方法获取uuid
参数:appid : wx782c26e4c19acffb ;fun : new ;lang: zh_CN ;_ : 时间戳
2、get方法获取二维码
url:https://login.weixin.qq.com/qrcode/{uuid}
把上一步获得uuid赋到url后边