微信公众号开发网页授权获取用户基本信息
如果用户在微信客户端中访问第三方网页,公众号可以通过微信网页授权机制,来获取用户基本信息,进而实现业务逻辑。
注意:网页授权两种方式 更多网页授权请查阅官网文档:网页授权 静默授权静默授权即可以在用户关注的的时候,获取用户基本信息,此过程用户无感知。 第一步,通过工厂类 转发请求 /// <returns></returns> public string HandleRequest() { string response = string.Empty; EventMessage em = EventMessage.LoadFromXml(RequestXml); if (em != null) { switch (em.Event.ToLower()) { case ("subscribe"): response = SubscribeEventHandler(em);//通过工厂类分发过来的请求,匹配到关注事件 break; case ("unsubscribe"): response = Un_SubscribeEventHandler(em); break; case "click": response = ClickEventHandler(em); break; } } return response; } 第二步,写用户关注事件 WeChat.Messages.TextMessage tm = = em.FromUserName; tm.FromUserName = em.ToUserName; tm.CreateTime == return tm.GenerateContent(); 第三步,根据得到的OpenId及accesstoken,即可获取用户基本信息(此处演示是将该用户存入数据库中) /// <summary> /// 根据OpenId将此条粉丝记录插入数据库中 /// </summary> /// <param name="FromUserName"></param> /// <param name="ToUserName"></param> public void ShowUserInfo(string FromUserName, string ToUserName) { try { Models.Users user = new Models.Users(); DAL.User userInfo = new DAL.User(); //获取accesstoken,获取用户基本信息需要Openid和accesstoken即可 accesstoken = Utility.Context.AccessToken; string url = string.Format("https://api.weixin.qq.com/cgi-bin/user/info?access_token={0}&openid={1}&lang=zh_CN", accesstoken, FromUserName); string result = HttpUtility.GetData(url); XDocument doc = XmlUtility.ParseJson(result, "root"); XElement root = doc.Root; if (root != null) { #region 取值/存值 subscribe = root.Element("subscribe").Value;//是否关注 1 是关注 nickname = root.Element("nickname").Value; //昵称 sex = root.Element("sex").Value; //性别什么 headimgurl = root.Element("headimgurl").Value; //头像url province = root.Element("province").Value;//地区 country = root.Element("country").Value; language = root.Element("language").Value; subscribe_time = root.Element("subscribe_time").Value; DateTime create_time = Common.GetTime(subscribe_time);//将时间戳转换为当前时间 city = root.Element("city").Value; user.OpenID = FromUserName;//OpenID即粉丝ID user.PublicId = ToUserName; user.UserID = FromUserName; user.NickName = nickname; user.Sex = int.Parse(sex); user.Subscribe = int.Parse(subscribe); user.Country = country; user.Province = province; user.City = city; user.CreateDate = create_time; user.HeadimgUrl = headimgurl; //将user实体存入数据库中 bool show = _user.Add(user); #endregion } } catch { throw (new ArgumentNullException()); } } 上面代码中 AccessToken的实现,新建一个Context类即可 private static DateTime GetAccessToken_Time; /// <summary> /// 过期时间为7200秒 /// </summary> private static int Expires_Period = 7200; /// <summary> /// /// </summary> private static string mAccessToken; public static string AppID = "换成相应公众号的即可"; public static string AppSecret = "换成相应公众号的即可"; /// <summary> /// 调用获取ACCESS_TOKEN,包含判断是否过期 /// </summary> public static string AccessToken { get { //如果为空,或者过期,需要重新获取 if (string.IsNullOrEmpty(mAccessToken) || HasExpired()) { //获取access_token mAccessToken = GetAccessToken(AppID, AppSecret); } return mAccessToken; } } /// <summary> /// 获取ACCESS_TOKEN方法 /// </summary> /// <param name="appId"></param> /// <param name="appSecret"></param> /// <returns></returns> private static string GetAccessToken(string appId, string appSecret) { string url = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", appId, appSecret); string result = HttpUtility.GetData(url); XDocument doc = XmlUtility.ParseJson(result, "root"); XElement root = doc.Root; if (root != null) { XElement access_token = root.Element("access_token"); if (access_token != null) { GetAccessToken_Time = DateTime.Now; if (root.Element("expires_in") != null) { Expires_Period = int.Parse(root.Element("expires_in").Value); } return access_token.Value; } else { GetAccessToken_Time = DateTime.MinValue; } } return null; } /// <summary> /// 判断Access_token是否过期 /// </summary> /// <returns>bool</returns> private static bool HasExpired() { if (GetAccessToken_Time != null) { //过期时间,允许有一定的误差,一分钟。获取时间消耗 if (DateTime.Now > GetAccessToken_Time.AddSeconds(Expires_Period).AddSeconds(-60)) { return true; } } return false; } GetData的实现 public static string GetData(string url) { return SendGetHttpRequest(url, "application/x-www-form-urlencoded"); } ParseJson的实现 public static XDocument ParseJson(string json, string rootName) { return JsonConvert.DeserializeXNode(json, rootName); } 关于第三步的 HttpUtility类中还有一些其他公用帮助方法,在这里一并放出,调用即可 /// <summary> /// 发送请求 /// </summary> /// <param name="url">Url地址</param> /// <param name="data">数据</param> public static string SendHttpRequest(string url, string data) { return SendPostHttpRequest(url, "application/x-www-form-urlencoded", data); } /// <summary> /// /// </summary> /// <param name="url"></param> /// <returns></returns> public static string GetData(string url) { return SendGetHttpRequest(url, "application/x-www-form-urlencoded"); } /// <summary> /// 发送请求 /// </summary> /// <param name="url">Url地址</param> /// <param name="method">方法(post或get)</param> /// <param name="method">数据类型</param> /// <param name="requestData">数据</param> public static string SendPostHttpRequest(string url, string contentType, string requestData) { WebRequest request = (WebRequest)HttpWebRequest.Create(url); request.Method = "POST"; byte[] postBytes = null; request.ContentType = contentType; postBytes = Encoding.UTF8.GetBytes(requestData); request.ContentLength = postBytes.Length; using (Stream outstream = request.GetRequestStream()) { outstream.Write(postBytes, 0, postBytes.Length); } string result = string.Empty; using (WebResponse response = request.GetResponse()) { if (response != null) { using (Stream stream = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) { result = reader.ReadToEnd(); } } } } return result; } /// <summary> /// 发送请求 /// </summary> /// <param name="url">Url地址</param> /// <param name="method">方法(post或get)</param> /// <param name="method">数据类型</param> /// <param name="requestData">数据</param> public static string SendGetHttpRequest(string url, string contentType) { WebRequest request = (WebRequest)HttpWebRequest.Create(url); request.Method = "GET"; request.ContentType = contentType; string result = string.Empty; using (WebResponse response = request.GetResponse()) { if (response != null) { using (Stream stream = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) { result = reader.ReadToEnd(); } } } } return result; } View Code 顺便提下上文中用到的User类如下 public class Users { /// <summary> /// 全局凭证唯一Id /// </summary> public string OpenID { get; set; } /// <summary> /// 公众号Id /// </summary> public string PublicId { get; set; } /// <summary> /// 用户Id /// </summary> public string UserID { get; set; } /// <summary> /// 昵称 /// </summary> public string NickName { get; set; } /// <summary> /// 性别 1是男 0是女 /// </summary> public int Sex { get; set; } /// <summary> /// 是否关注 1是关注 /// </summary> public int Subscribe { get; set; } /// <summary> /// 国家 /// </summary> public string Country { get; set; } /// <summary> /// 地区 /// </summary> public string Province { get; set; } /// <summary> /// 城市 /// </summary> public string City { get; set; } /// <summary> /// 关注时间 /// </summary> public DateTime CreateDate { get; set; } /// <summary> /// 用户头像 /// </summary> public string HeadimgUrl { get; set; } /// <summary> /// 第三方平台Id,可为空 /// </summary> public string UnionID { get; set; } /// <summary> /// 用户取消关注时间 /// </summary> public DateTime Un_Subscribe_Time { get; set; } } 演示效果数据库中此时是存在10条数据的,当点击关注此公众号的时候,就将此用户的基本信息存入数据库了,数据库刷新后变成11条数据
网页授权流程具体介绍依然可参考官网文档:网页授权 第一步,判断该用户是否获取授权,若没有授权,则跳转至授权页面,若授权,则获取基本信息 核心代码 /// <summary> /// 获取授权用户的基本信息,包括头像,姓名,等等(推荐方法) /// </summary> /// <param name="accessToken">用户授权之后的accessToken</param> /// <param name="openid">用户授权之后的openid</param> /// <returns></returns> public static ShouQuanWeiXinUserInfo GetShouQuanMessage() { //先判断是否有获取到用户授权的Code,HttpContext.Current.Session["ShouquanCode"] if (HttpContext.Current.Session["ShouquanCode"] == null|| HttpContext.Current.Session["ShouquanCode"].ToString()=="") { HttpContext.Current.Session["ShouquanCode"] = "123"; //用户授权的Code GetShouQuanCodeUrl(HttpContext.Current.Request.Url.AbsoluteUri); } else if(HttpContext.Current.Request.QueryString["code"] == null || HttpContext.Current.Request.QueryString["code"] == "") { //用户授权的Code GetShouQuanCodeUrl(HttpContext.Current.Request.Url.AbsoluteUri); } else { var model = ShouQuanAccessToken(HttpContext.Current.Request.QueryString["code"]); var url = $"http://www.php.cn/{model.access_token}&openid={model.openid}&lang=zh_CN"; string gethtml = MyHttpHelper.HttpGet(url); var ac = JsonHelpers.ToObject<ShouQuanWeiXinUserInfo>(gethtml); return ac; } return null; } 其中,用户授权的code方法如下: /// <summary> /// 重新获取用户授权的Code,可以获取用户的基本信息(头像,姓名,等等)(推荐用的方法) /// </summary> /// <param name="url">目标Url</param> /// <returns></returns> public static void GetShouQuanCodeUrl(string url) { string CodeUrl = ""; //加密过的url string value = HttpUtility.UrlEncode(url); //用户授权后的Code CodeUrl = $"http://www.php.cn/{Appid}&redirect_uri={value}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"; System.Web.HttpContext.Current.Response.Redirect(CodeUrl);//先跳转到微信的服务器,取得code后会跳回来这页面的 } 其中ShouQuanAccessToken方法 /// <summary> //用户授权之后,获取授权的Access_Token与基本的Access_Token是不同的(推荐方法) /// </summary> /// <param name="code">用户授权之后的Code</param> /// <returns></returns> public static OauthAccessToken ShouQuanAccessToken(string code) { var url = $"http://www.php.cn/{Appid}&secret={Secret}&code={code}&grant_type=authorization_code"; string gethtml = MyHttpHelper.HttpGet(url); OauthAccessToken ac = new OauthAccessToken(); ac = JsonHelpers.ToObject<OauthAccessToken>(gethtml); return ac; } 用户实体 public class OauthAccessToken { public string access_token { get; set; } public string expires_in { get; set; } public string refresh_token { get; set; } public string openid { get; set; } public string scope { get; set; } } 其中用到的MyHttpHelper公众类如下 /// <summary> /// Http连接操作帮助类 /// </summary> public class HttpHelpers { #region 预定义方法或者变更 //默认的编码 private Encoding encoding = Encoding.Default; //Post数据编码 private Encoding postencoding = Encoding.Default; //HttpWebRequest对象用来发起请求 private HttpWebRequest request = null; //获取影响流的数据对象 private HttpWebResponse response = null; /// <summary> /// 根据相传入的数据,得到相应页面数据 /// </summary> /// <param name="item">参数类对象</param> /// <returns>返回HttpResult类型</returns> public HttpResult GetHtml(HttpItem item) { //返回参数 HttpResult result = new HttpResult(); try { //准备参数 SetRequest(item); } catch (Exception ex) { return new HttpResult() { Cookie = string.Empty, Header = null, Html = ex.Message, StatusDescription = "配置参数时出错:" + ex.Message }; } try { #region 得到请求的response using (response = (HttpWebResponse)request.GetResponse()) { result.StatusCode = response.StatusCode; result.StatusDescription = response.StatusDescription; result.Header = response.Headers; if (response.Cookies != null) result.CookieCollection = response.Cookies; if (response.Headers["set-cookie"] != null) result.Cookie = response.Headers["set-cookie"]; byte[] ResponseByte = null; using (MemoryStream _stream = new MemoryStream()) { //GZIIP处理 if (response.ContentEncoding != null && response.ContentEncoding.Equals("gzip", StringComparison.InvariantCultureIgnoreCase)) { //开始读取流并设置编码方式 new GZipStream(response.GetResponseStream(), CompressionMode.Decompress).CopyTo(_stream, 10240); } else { //开始读取流并设置编码方式 response.GetResponseStream().CopyTo(_stream, 10240); } //获取Byte ResponseByte = _stream.ToArray(); } if (ResponseByte != null & ResponseByte.Length > 0) { //是否返回Byte类型数据 if (item.ResultType == ResultType.Byte) result.ResultByte = ResponseByte; //从这里开始我们要无视编码了 if (encoding == null) { Match meta = Regex.Match(Encoding.Default.GetString(ResponseByte), "<meta([^<]*)charset=([^<]*)[/"']", RegexOptions.IgnoreCase); string c = (meta.Groups.Count > 1) ? meta.Groups[2].Value.ToLower().Trim() : string.Empty; if (c.Length > 2) { try { if (c.IndexOf(" ") > 0) c = c.Substring(0, c.IndexOf(" ")); encoding = Encoding.GetEncoding(c.Replace("/"", "").Replace("'", "").Replace(";", "").Replace("iso-8859-1", "gbk").Trim()); } catch { if (string.IsNullOrEmpty(response.CharacterSet)) encoding = Encoding.UTF8; else encoding = Encoding.GetEncoding(response.CharacterSet); } } else { if (string.IsNullOrEmpty(response.CharacterSet)) encoding = Encoding.UTF8; else encoding = Encoding.GetEncoding(response.CharacterSet); } } //得到返回的HTML result.Html = encoding.GetString(ResponseByte); } else { //得到返回的HTML //result.Html = "本次请求并未返回任何数据"; result.Html = ""; } } #endregion } catch (WebException ex) { //这里是在发生异常时返回的错误信息 response = (HttpWebResponse)ex.Response; result.Html = ex.Message; if (response != null) { result.StatusCode = response.StatusCode; result.StatusDescription = response.StatusDescription; } } catch (Exception ex) { result.Html = ex.Message; } if (item.IsToLower) result.Html = result.Html.ToLower(); return result; } /// <summary> /// 为请求准备参数 /// </summary> ///<param name="item">参数列表</param> private void SetRequest(HttpItem item) { // 验证证书 SetCer(item); //设置Header参数 if (item.Header != null && item.Header.Count > 0) foreach (string key in item.Header.AllKeys) { request.Headers.Add(key, item.Header[key]); } // 设置代理 //SetProxy(item); if (item.ProtocolVersion != null) request.ProtocolVersion = item.ProtocolVersion; request.ServicePoint.Expect100Continue = item.Expect100Continue; //请求方式Get或者Post request.Method = item.Method; request.Timeout = item.Timeout; request.KeepAlive = item.KeepAlive; request.ReadWriteTimeout = item.ReadWriteTimeout; if (!string.IsNullOrWhiteSpace(item.Host)) { request.Host = item.Host; } //Accept request.Accept = item.Accept; //ContentType返回类型 request.ContentType = item.ContentType; //UserAgent客户端的访问类型,包括浏览器版本和操作系统信息 request.UserAgent = item.UserAgent; // 编码 encoding = item.Encoding; //设置安全凭证 request.Credentials = item.ICredentials; //设置Cookie SetCookie(item); //来源地址 request.Referer = item.Referer; //是否执行跳转功能 request.AllowAutoRedirect = item.Allowautoredirect; //设置Post数据 SetPostData(item); //设置最大连接 if (item.Connectionlimit > 0) request.ServicePoint.ConnectionLimit = item.Connectionlimit; } /// <summary> /// 设置证书 /// </summary> /// <param name="item"></param> private void SetCer(HttpItem item) { if (!string.IsNullOrWhiteSpace(item.CerPath)) { //这一句一定要写在创建连接的前面。使用回调的方法进行证书验证。 ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult); //初始化对像,并设置请求的URL地址 request = (HttpWebRequest)WebRequest.Create(item.URL); SetCerList(item); //将证书添加到请求里 request.ClientCertificates.Add(new X509Certificate(item.CerPath)); } else { //初始化对像,并设置请求的URL地址 request = (HttpWebRequest)WebRequest.Create(item.URL); SetCerList(item); } } /// <summary> /// 设置多个证书 /// </summary> /// <param name="item"></param> private void SetCerList(HttpItem item) { if (item.ClentCertificates != null && item.ClentCertificates.Count > 0) { foreach (X509Certificate c in item.ClentCertificates) { request.ClientCertificates.Add(c); } } } /// <summary> /// 设置Cookie /// </summary> /// <param name="item">Http参数</param> private void SetCookie(HttpItem item) { if (!string.IsNullOrEmpty(item.Cookie)) request.Headers[HttpRequestHeader.Cookie] = item.Cookie; //设置CookieCollection if (item.ResultCookieType == ResultCookieType.CookieCollection) { request.CookieContainer = new CookieContainer(); if (item.CookieCollection != null && item.CookieCollection.Count > 0) request.CookieContainer.Add(item.CookieCollection); } } /// <summary> /// 设置Post数据 /// </summary> /// <param name="item">Http参数</param> private void SetPostData(HttpItem item) { //验证在得到结果时是否有传入数据 if (request.Method.Trim().ToLower().Contains("post")) { if (item.PostEncoding != null) { postencoding = item.PostEncoding; } byte[] buffer = null; //写入Byte类型 if (item.PostDataType == PostDataType.Byte && item.PostdataByte != null && item.PostdataByte.Length > 0) { //验证在得到结果时是否有传入数据 buffer = item.PostdataByte; }//写入文件 else if (item.PostDataType == PostDataType.FilePath && !string.IsNullOrWhiteSpace(item.Postdata)) { StreamReader r = new StreamReader(item.Postdata, postencoding); buffer = postencoding.GetBytes(r.ReadToEnd()); r.Close(); } //写入字符串 else if (!string.IsNullOrWhiteSpace(item.Postdata)) { buffer = postencoding.GetBytes(item.Postdata); } if (buffer != null) { request.ContentLength = buffer.Length; request.GetRequestStream().Write(buffer, 0, buffer.Length); } } } /// <summary> /// 设置代理 /// </summary> /// <param name="item">参数对象</param> private void SetProxy(HttpItem item) { bool isIeProxy = item.ProxyIp.ToLower().Contains("ieproxy"); if (!string.IsNullOrWhiteSpace(item.ProxyIp) && !isIeProxy) { //设置代理服务器 if (item.ProxyIp.Contains(":")) { string[] plist = item.ProxyIp.Split(':'); WebProxy myProxy = new WebProxy(plist[0].Trim(), Convert.ToInt32(plist[1].Trim())); //建议连接 myProxy.Credentials = new NetworkCredential(item.ProxyUserName, item.ProxyPwd); //给当前请求对象 request.Proxy = myProxy; } else { WebProxy myProxy = new WebProxy(item.ProxyIp, false); //建议连接 myProxy.Credentials = new NetworkCredential(item.ProxyUserName, item.ProxyPwd); //给当前请求对象 request.Proxy = myProxy; } } else if (isIeProxy) { //设置为IE代理 } else { request.Proxy = item.WebProxy; } } /// <summary> /// 回调验证证书问题 /// </summary> /// <param name="sender">流对象</param> /// <param name="certificate">证书</param> /// <param name="chain">X509Chain</param> /// <param name="errors">SslPolicyErrors</param> /// <returns>bool</returns> public bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; } #endregion } /// <summary> /// Http请求参考类 /// </summary> public class HttpItem { /// <summary> /// 请求URL必须填写 /// </summary> public string URL { get; set; } string _Method = "GET"; /// <summary> /// 请求方式默认为GET方式,当为POST方式时必须设置Postdata的值 /// </summary> public string Method { get { return _Method; } set { _Method = value; } } int _Timeout = 100000; /// <summary> /// 默认请求超时时间 /// </summary> public int Timeout { get { return _Timeout; } set { _Timeout = value; } } int _ReadWriteTimeout = 30000; /// <summary> /// 默认写入Post数据超时间 /// </summary> public int ReadWriteTimeout { get { return _ReadWriteTimeout; } set { _ReadWriteTimeout = value; } } /// <summary> /// 设置Host的标头信息 /// </summary> public string Host { get; set; } Boolean _KeepAlive = true; /// <summary> /// 获取或设置一个值,该值指示是否与 Internet 资源建立持久性连接默认为true。 /// </summary> public Boolean KeepAlive { get { return _KeepAlive; } set { _KeepAlive = value; } } string _Accept = "text/html, application/xhtml+xml, */*"; /// <summary> /// 请求标头值 默认为text/html, application/xhtml+xml, */* /// </summary> public string Accept { get { return _Accept; } set { _Accept = value; } } string _ContentType = "text/html"; /// <summary> /// 请求返回类型默认 text/html /// </summary> public string ContentType { get { return _ContentType; } set { _ContentType = value; } } string _UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)"; /// <summary> /// 客户端访问信息默认Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0) /// </summary> public string UserAgent { get { return _UserAgent; } set { _UserAgent = value; } } /// <summary> /// 返回数据编码默认为NUll,可以自动识别,一般为utf-8,gbk,gb2312 /// </summary> public Encoding Encoding { get; set; } private PostDataType _PostDataType = PostDataType.String; /// <summary> /// Post的数据类型 /// </summary> public PostDataType PostDataType { get { return _PostDataType; } set { _PostDataType = value; } } /// <summary> /// Post请求时要发送的字符串Post数据 /// </summary> public string Postdata { get; set; } /// <summary> /// Post请求时要发送的Byte类型的Post数据 /// </summary> public byte[] PostdataByte { get; set; } /// <summary> /// Cookie对象集合 /// </summary> public CookieCollection CookieCollection { get; set; } /// <summary> /// 请求时的Cookie /// </summary> public string Cookie { get; set; } /// <summary> /// 来源地址,上次访问地址 /// </summary> public string Referer { get; set; } /// <summary> /// 证书绝对路径 /// </summary> public string CerPath { get; set; } /// <summary> /// 设置代理对象,不想使用IE默认配置就设置为Null,而且不要设置ProxyIp /// </summary> public WebProxy WebProxy { get; set; } private Boolean isToLower = false; /// <summary> /// 是否设置为全文小写,默认为不转化 /// </summary> public Boolean IsToLower { get { return isToLower; } set { isToLower = value; } } private Boolean allowautoredirect = false; /// <summary> /// 支持跳转页面,查询结果将是跳转后的页面,默认是不跳转 /// </summary> public Boolean Allowautoredirect { get { return allowautoredirect; } set { allowautoredirect = value; } } private int connectionlimit = 1024; /// <summary> /// 最大连接数 /// </summary> public int Connectionlimit { get { return connectionlimit; } set { connectionlimit = value; } } /// <summary> /// 代理Proxy 服务器用户名 /// </summary> public string ProxyUserName { get; set; } /// <summary> /// 代理 服务器密码 /// </summary> public string ProxyPwd { get; set; } /// <summary> /// 代理 服务IP,如果要使用IE代理就设置为ieproxy /// </summary> public string ProxyIp { get; set; } private ResultType resulttype = ResultType.String; /// <summary> /// 设置返回类型String和Byte /// </summary> public ResultType ResultType { get { return resulttype; } set { resulttype = value; } } private WebHeaderCollection header = new WebHeaderCollection(); /// <summary> /// header对象 /// </summary> public WebHeaderCollection Header { get { return header; } set { header = value; } } /// <summary> // 获取或设置用于请求的 HTTP 版本。返回结果:用于请求的 HTTP 版本。默认为 System.Net.HttpVersion.Version11。 /// </summary> public Version ProtocolVersion { get; set; } private Boolean _expect100continue = true; /// <summary> /// 获取或设置一个 System.Boolean 值,该值确定是否使用 100-Continue 行为。如果 POST 请求需要 100-Continue 响应,则为 true;否则为 false。默认值为 true。 /// </summary> public Boolean Expect100Continue { get { return _expect100continue; } set { _expect100continue = value; } } /// <summary> /// 设置509证书集合 /// </summary> public X509CertificateCollection ClentCertificates { get; set; } /// <summary> /// 设置或获取Post参数编码,默认的为Default编码 /// </summary> public Encoding PostEncoding { get; set; } private ResultCookieType _ResultCookieType = ResultCookieType.String; /// <summary> /// Cookie返回类型,默认的是只返回字符串类型 /// </summary> public ResultCookieType ResultCookieType { get { return _ResultCookieType; } set { _ResultCookieType = value; } } private ICredentials _ICredentials = CredentialCache.DefaultCredentials; /// <summary> /// 获取或设置请求的身份验证信息。 /// </summary> public ICredentials ICredentials { get { return _ICredentials; } set { _ICredentials = value; } } } /// <summary> /// Http返回参数类 /// </summary> public class HttpResult { /// <summary> /// Http请求返回的Cookie /// </summary> public string Cookie { get; set; } /// <summary> /// Cookie对象集合 /// </summary> public CookieCollection CookieCollection { get; set; } /// <summary> /// 返回的String类型数据 只有ResultType.String时才返回数据,其它情况为空 /// </summary> public string Html { get; set; } /// <summary> /// 返回的Byte数组 只有ResultType.Byte时才返回数据,其它情况为空 /// </summary> public byte[] ResultByte { get; set; } /// <summary> /// header对象 /// </summary> public WebHeaderCollection Header { get; set; } /// <summary> /// 返回状态说明 /// </summary> public string StatusDescription { get; set; } /// <summary> /// 返回状态码,默认为OK /// </summary> public HttpStatusCode StatusCode { get; set; } } /// <summary> /// 返回类型 /// </summary> public enum ResultType { /// <summary> /// 表示只返回字符串 只有Html有数据 /// </summary> String, /// <summary> /// 表示返回字符串和字节流 ResultByte和Html都有数据返回 /// </summary> Byte } /// <summary> /// Post的数据格式默认为string /// </summary> public enum PostDataType { /// <summary> /// 字符串类型,这时编码Encoding可不设置 /// </summary> String, /// <summary> /// Byte类型,需要设置PostdataByte参数的值编码Encoding可设置为空 /// </summary> Byte, /// <summary> /// 传文件,Postdata必须设置为文件的绝对路径,必须设置Encoding的值 /// </summary> FilePath } /// <summary> /// Cookie返回类型 /// </summary> public enum ResultCookieType { /// <summary> /// 只返回字符串类型的Cookie /// </summary> String, /// <summary> /// CookieCollection格式的Cookie集合同时也返回String类型的cookie /// </summary> CookieCollection } /// <summary>HttpHelper的2次封装函数 作者: /// </summary> public class MyHttpHelper { #region 公共函数 /// <summary>返回 HTML 字符串的编码结果</summary> /// <param name="str">字符串</param> /// <returns>编码结果</returns> public static string HtmlEncode(string str) { if (string.IsNullOrEmpty(str)) { return ""; } return str.Length > 0 ? HttpUtility.HtmlEncode(str) : ""; } /// <summary>返回 HTML 字符串的解码结果</summary> /// <param name="str">字符串</param> /// <returns>解码结果</returns> public static string HtmlDecode(string str) { if (string.IsNullOrEmpty(str)) { return ""; } return str.Length > 0 ? HttpUtility.HtmlDecode(str) : ""; } /// <summary> /// 根据指定的编码对RUl进行解码 /// </summary> /// <param name="str">要解码的字符串</param> /// <param name="encoding">要进行解码的编码方式</param> /// <returns></returns> public static string UrlDecode(string str, Encoding encoding = null) { if (string.IsNullOrEmpty(str)) { return ""; } if (str.Length == 0) { return ""; } if (encoding == null) { return HttpUtility.UrlDecode(str); } else { return HttpUtility.UrlDecode(str, encoding); } } /// <summary>根据指定的编码对URL进行编码</summary> /// <param name="str">要编码的URL</param> /// <param name="encoding">要进行编码的编码方式</param> /// <returns></returns> public static string UrlEncode(string str, Encoding encoding = null) { if (string.IsNullOrEmpty(str)) { return ""; } if (str.Length == 0) { return ""; } if (encoding == null) { return HttpUtility.UrlEncode(str); } else { return HttpUtility.UrlEncode(str, encoding); } } /// <summary> /// 根据 charSet 返回 Encoding /// </summary> /// <param name="charSet">"gb2312" or "utf-8",默认: "" == "utf-8"</param> /// <returns></returns> public static Encoding GetEncoding(string charSet) { Encoding en = Encoding.Default; if (charSet == "gb2312") { en = Encoding.GetEncoding("gb2312"); } else if (charSet == "utf-8") { en = Encoding.UTF8; } return en; } #endregion #region Post /// <summary>HTTP Get方式请求数据</summary> /// <param name="url">URL</param> /// <param name="param">user=123123 & pwd=1231313"</param> /// <param name="charSet">"gb2312" or "utf-8",默认: "" == "utf-8"</param> /// <returns></returns> public static string HttpPost(string url, string param, string charSet = "utf-8") { HttpHelpers http = new HttpHelpers(); HttpItem item = new HttpItem() { URL = url, Encoding = GetEncoding(charSet),//编码格式(utf-8,gb2312,gbk) 可选项 默认类会自动识别 Method = "post",//URL 可选项 默认为Get Postdata = param }; //得到HTML代码 HttpResult result = http.GetHtml(item); //取出返回的Cookie //string cookie = result.Cookie; //返回的Html内容 string html = result.Html; if (result.StatusCode == System.Net.HttpStatusCode.OK) { return html; } //string statusCodeDescription = result.StatusDescription; return ""; } #endregion #region Get /// <summary>HTTP Get方式请求数据</summary> /// <param name="url">URL</param> /// <param name="charSet">"gb2312" or "utf-8",默认: "" == "utf-8"</param> /// <returns></returns> public static string HttpGet(string url, string charSet = "utf-8") { HttpHelpers http = new HttpHelpers(); HttpItem item = new HttpItem() { URL = url, Encoding = GetEncoding(charSet), Method = "get" }; //得到HTML代码 HttpResult result = http.GetHtml(item); //取出返回的Cookie //string cookie = result.Cookie; //返回的Html内容 string html = result.Html; if (result.StatusCode == System.Net.HttpStatusCode.OK) { return html; } //string statusCodeDescription = result.StatusDescription; return ""; } /// <summary>POST客服消息/summary> /// <param name="url">URL</param> /// <param name="postData">内容</param> /// <returns>消息状态</returns> public static string GetPage(string posturl, string postData) { Stream outstream = null; Stream instream = null; StreamReader sr = null; HttpWebResponse response = null; HttpWebRequest request = null; Encoding encoding = Encoding.UTF8; byte[] data = encoding.GetBytes(postData); // 准备请求... try { // 设置参数 request = WebRequest.Create(posturl) as HttpWebRequest; CookieContainer cookieContainer = new CookieContainer(); request.CookieContainer = cookieContainer; request.AllowAutoRedirect = true; request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = data.Length; outstream = request.GetRequestStream(); outstream.Write(data, 0, data.Length); outstream.Close(); //发送请求并获取相应回应数据 response = request.GetResponse() as HttpWebResponse; //直到request.GetResponse()程序才开始向目标网页发送Post请求 instream = response.GetResponseStream(); sr = new StreamReader(instream, encoding); //返回结果网页(html)代码 string content = sr.ReadToEnd(); string err = string.Empty; return content; } catch (Exception ex) { string err = ex.Message; return err; } } #endregion } View Code 封装的JsonHelpers类如下 #region 通用 /// <summary>检查字符串是否json格式</summary> /// <param name="jText"></param> /// <returns></returns> public static bool IsJson(string jText) { if (string.IsNullOrEmpty(jText) || jText.Length < 3) { return false; } if (jText.Substring(0, 2) == "{/"" || jText.Substring(0, 3) == "[{/"") { return true; } return false; } /// <summary>检查字符串是否json格式数组</summary> /// <param name="jText"></param> /// <returns></returns> public static bool IsJsonRs(string jText) { if (string.IsNullOrEmpty(jText) || jText.Length < 3) { return false; } if (jText.Substring(0, 3) == "[{/"") { return true; } return false; } /// <summary>格式化 json</summary> /// <param name="jText"></param> /// <returns></returns> public static string Fmt_Null(string jText) { return StringHelper.ReplaceString(jText, ":null,", ":/"/",", true); } /// <summary>格式化 json ,删除左右二边的[]</summary> /// <param name="jText"></param> /// <returns></returns> public static string Fmt_Rs(string jText) { jText = jText.Trim(); jText = jText.Trim('['); jText = jText.Trim(']'); return jText; } #endregion #region Json序列化 /// <summary>序列化</summary> /// <param name="obj">object </param> /// <returns></returns> public static string ToJson(object obj) { var idtc = new Newtonsoft.Json.Converters.IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd hh:mm:ss" }; return JsonConvert.SerializeObject(obj, idtc); } /// <summary>序列化--sql</summary> /// <param name="dt">DataTable</param> /// <returns></returns> public static string ToJson_FromSQL(DataTable dt) { string ss = ToJson(dt); dt.Dispose(); return ss; } #endregion #region Json反序列化 /// <summary>反序列化</summary> /// <param name="jText"></param> /// <returns></returns> public static DataTable ToDataTable(string jText) { if (string.IsNullOrEmpty(jText)) { return null; } else { try { return JsonConvert.DeserializeObject<DataTable>(jText); } catch { return null; } } } /// <summary>反序列化</summary> /// <typeparam name="T">类型</typeparam> /// <param name="jText">json字符串</param> /// <returns>类型数据</returns> public static T ToObject<T>(string jText) { return (T)JsonConvert.DeserializeObject(jText, typeof(T)); } #endregion View Code 其中,如果是VS2015以下的,可以将url字符串改成string.format("")方式 调用取值的方式 效果展示点击公众号链接效果如下:
更多微信公众号开发网页授权获取用户基本信息 相关文章请关注PHP中文网! |