如果用户在微信客户端中访问第三方网页,公众号可以通过微信网页授权机制,来获取用户基本信息,进而实现业务逻辑。
注意:网页授权两种方式
更多网页授权请查阅官网文档:网页授权
静默授权即可以在用户关注的的时候,获取用户基本信息,此过程用户无感知。
第一步,通过工厂类 转发请求
///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; }
第二步,写用户关注事件
////// 用户关注 /// /// /// public string SubscribeEventHandler(EventMessage em) { //回复欢迎消息 WeChat.Messages.TextMessage tm = new WeChat.Messages.TextMessage(); tm.ToUserName = em.FromUserName;//OpenId tm.FromUserName = em.ToUserName;//公众号原始Id tm.CreateTime = Common.GetNowTime(); tm.Content = "欢迎您关注****,我是服务小二,有事就问我~\n\n"; tm.GenerateContent(); //如有业务需要,可在此处先判断该用户是否已关注
//此处得到OpenId
show.ShowUserInfo(em.FromUserName,em.ToUserName);
return tm.GenerateContent();
}
第三步,根据得到的OpenId及accesstoken,即可获取用户基本信息(此处演示是将该用户存入数据库中)
////// 根据OpenId将此条粉丝记录插入数据库中 /// /// /// 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; ////// 过期时间为7200秒 /// private static int Expires_Period = 7200; /// /// /// private static string mAccessToken; public static string AppID = "换成相应公众号的即可"; public static string AppSecret = "换成相应公众号的即可"; /// /// 调用获取ACCESS_TOKEN,包含判断是否过期 /// public static string AccessToken { get { //如果为空,或者过期,需要重新获取 if (string.IsNullOrEmpty(mAccessToken) || HasExpired()) { //获取access_token mAccessToken = GetAccessToken(AppID, AppSecret); } return mAccessToken; } } /// /// 获取ACCESS_TOKEN方法 /// /// /// /// 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; } /// /// 判断Access_token是否过期 /// /// bool 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类中还有一些其他公用帮助方法,在这里一并放出,调用即可
////// 发送请求 /// /// Url地址 /// 数据 public static string SendHttpRequest(string url, string data) { return SendPostHttpRequest(url, "application/x-www-form-urlencoded", data); } /// /// /// /// /// public static string GetData(string url) { return SendGetHttpRequest(url, "application/x-www-form-urlencoded"); } /// /// 发送请求 /// /// Url地址 /// 方法(post或get) /// 数据类型 /// 数据 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; } /// /// 发送请求 /// /// Url地址 /// 方法(post或get) /// 数据类型 /// 数据 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; }
顺便提下上文中用到的User类如下
public class Users { ////// 全局凭证唯一Id /// public string OpenID { get; set; } /// /// 公众号Id /// public string PublicId { get; set; } /// /// 用户Id /// public string UserID { get; set; } /// /// 昵称 /// public string NickName { get; set; } /// /// 性别 1是男 0是女 /// public int Sex { get; set; } /// /// 是否关注 1是关注 /// public int Subscribe { get; set; } /// /// 国家 /// public string Country { get; set; } /// /// 地区 /// public string Province { get; set; } /// /// 城市 /// public string City { get; set; } /// /// 关注时间 /// public DateTime CreateDate { get; set; } /// /// 用户头像 /// public string HeadimgUrl { get; set; } /// /// 第三方平台Id,可为空 /// public string UnionID { get; set; } /// /// 用户取消关注时间 /// public DateTime Un_Subscribe_Time { get; set; } }
数据库中此时是存在10条数据的,当点击关注此公众号的时候,就将此用户的基本信息存入数据库了,数据库刷新后变成11条数据
具体介绍依然可参考官网文档:网页授权
第一步,判断该用户是否获取授权,若没有授权,则跳转至授权页面,若授权,则获取基本信息
核心代码
////// 获取授权用户的基本信息,包括头像,姓名,等等(推荐方法) /// /// 用户授权之后的accessToken /// 用户授权之后的openid /// 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 = $"https://api.weixin.qq.com/sns/userinfo?access_token={model.access_token}&openid={model.openid}&lang=zh_CN"; string gethtml = MyHttpHelper.HttpGet(url); var ac = JsonHelpers.ToObject (gethtml); return ac; } return null; }
其中,用户授权的code方法如下:
////// 重新获取用户授权的Code,可以获取用户的基本信息(头像,姓名,等等)(推荐用的方法) /// /// 目标Url /// public static void GetShouQuanCodeUrl(string url) { string CodeUrl = ""; //加密过的url string value = HttpUtility.UrlEncode(url); //用户授权后的Code CodeUrl = $"https://open.weixin.qq.com/connect/oauth2/authorize?appid={Appid}&redirect_uri={value}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"; System.Web.HttpContext.Current.Response.Redirect(CodeUrl);//先跳转到微信的服务器,取得code后会跳回来这页面的 }
其中ShouQuanAccessToken方法
/////用户授权之后,获取授权的Access_Token与基本的Access_Token是不同的(推荐方法) /// /// 用户授权之后的Code /// public static OauthAccessToken ShouQuanAccessToken(string code) { var url = $"https://api.weixin.qq.com/sns/oauth2/access_token?appid={Appid}&secret={Secret}&code={code}&grant_type=authorization_code"; string gethtml = MyHttpHelper.HttpGet(url); OauthAccessToken ac = new OauthAccessToken(); ac = JsonHelpers.ToObject (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公众类如下
////// Http连接操作帮助类 /// public class HttpHelpers { #region 预定义方法或者变更 //默认的编码 private Encoding encoding = Encoding.Default; //Post数据编码 private Encoding postencoding = Encoding.Default; //HttpWebRequest对象用来发起请求 private HttpWebRequest request = null; //获取影响流的数据对象 private HttpWebResponse response = null; /// /// 根据相传入的数据,得到相应页面数据 /// /// 参数类对象 /// 返回HttpResult类型 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), "", 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; } /// /// 为请求准备参数 /// ///参数列表 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; } /// /// 设置证书 /// /// 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); } } /// /// 设置多个证书 /// /// private void SetCerList(HttpItem item) { if (item.ClentCertificates != null && item.ClentCertificates.Count > 0) { foreach (X509Certificate c in item.ClentCertificates) { request.ClientCertificates.Add(c); } } } /// /// 设置Cookie /// /// Http参数 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); } } /// /// 设置Post数据 /// /// Http参数 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); } } } /// /// 设置代理 /// /// 参数对象 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; } } /// /// 回调验证证书问题 /// /// 流对象 /// 证书 /// X509Chain /// SslPolicyErrors /// bool public bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; } #endregion } /// /// Http请求参考类 /// public class HttpItem { /// /// 请求URL必须填写 /// public string URL { get; set; } string _Method = "GET"; /// /// 请求方式默认为GET方式,当为POST方式时必须设置Postdata的值 /// public string Method { get { return _Method; } set { _Method = value; } } int _Timeout = 100000; /// /// 默认请求超时时间 /// public int Timeout { get { return _Timeout; } set { _Timeout = value; } } int _ReadWriteTimeout = 30000; /// /// 默认写入Post数据超时间 /// public int ReadWriteTimeout { get { return _ReadWriteTimeout; } set { _ReadWriteTimeout = value; } } /// /// 设置Host的标头信息 /// public string Host { get; set; } Boolean _KeepAlive = true; /// /// 获取或设置一个值,该值指示是否与 Internet 资源建立持久性连接默认为true。 /// public Boolean KeepAlive { get { return _KeepAlive; } set { _KeepAlive = value; } } string _Accept = "text/html, application/xhtml+xml, */*"; /// /// 请求标头值 默认为text/html, application/xhtml+xml, */* /// public string Accept { get { return _Accept; } set { _Accept = value; } } string _ContentType = "text/html"; /// /// 请求返回类型默认 text/html /// 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)"; /// /// 客户端访问信息默认Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0) /// public string UserAgent { get { return _UserAgent; } set { _UserAgent = value; } } /// /// 返回数据编码默认为NUll,可以自动识别,一般为utf-8,gbk,gb2312 /// public Encoding Encoding { get; set; } private PostDataType _PostDataType = PostDataType.String; /// /// Post的数据类型 /// public PostDataType PostDataType { get { return _PostDataType; } set { _PostDataType = value; } } /// /// Post请求时要发送的字符串Post数据 /// public string Postdata { get; set; } /// /// Post请求时要发送的Byte类型的Post数据 /// public byte[] PostdataByte { get; set; } /// /// Cookie对象集合 /// public CookieCollection CookieCollection { get; set; } /// /// 请求时的Cookie /// public string Cookie { get; set; } /// /// 来源地址,上次访问地址 /// public string Referer { get; set; } /// /// 证书绝对路径 /// public string CerPath { get; set; } /// /// 设置代理对象,不想使用IE默认配置就设置为Null,而且不要设置ProxyIp /// public WebProxy WebProxy { get; set; } private Boolean isToLower = false; /// /// 是否设置为全文小写,默认为不转化 /// public Boolean IsToLower { get { return isToLower; } set { isToLower = value; } } private Boolean allowautoredirect = false; /// /// 支持跳转页面,查询结果将是跳转后的页面,默认是不跳转 /// public Boolean Allowautoredirect { get { return allowautoredirect; } set { allowautoredirect = value; } } private int connectionlimit = 1024; /// /// 最大连接数 /// public int Connectionlimit { get { return connectionlimit; } set { connectionlimit = value; } } /// /// 代理Proxy 服务器用户名 /// public string ProxyUserName { get; set; } /// /// 代理 服务器密码 /// public string ProxyPwd { get; set; } /// /// 代理 服务IP,如果要使用IE代理就设置为ieproxy /// public string ProxyIp { get; set; } private ResultType resulttype = ResultType.String; /// /// 设置返回类型String和Byte /// public ResultType ResultType { get { return resulttype; } set { resulttype = value; } } private WebHeaderCollection header = new WebHeaderCollection(); /// /// header对象 /// public WebHeaderCollection Header { get { return header; } set { header = value; } } /// // 获取或设置用于请求的 HTTP 版本。返回结果:用于请求的 HTTP 版本。默认为 System.Net.HttpVersion.Version11。 /// public Version ProtocolVersion { get; set; } private Boolean _expect100continue = true; /// /// 获取或设置一个 System.Boolean 值,该值确定是否使用 100-Continue 行为。如果 POST 请求需要 100-Continue 响应,则为 true;否则为 false。默认值为 true。 /// public Boolean Expect100Continue { get { return _expect100continue; } set { _expect100continue = value; } } /// /// 设置509证书集合 /// public X509CertificateCollection ClentCertificates { get; set; } /// /// 设置或获取Post参数编码,默认的为Default编码 /// public Encoding PostEncoding { get; set; } private ResultCookieType _ResultCookieType = ResultCookieType.String; /// /// Cookie返回类型,默认的是只返回字符串类型 /// public ResultCookieType ResultCookieType { get { return _ResultCookieType; } set { _ResultCookieType = value; } } private ICredentials _ICredentials = CredentialCache.DefaultCredentials; /// /// 获取或设置请求的身份验证信息。 /// public ICredentials ICredentials { get { return _ICredentials; } set { _ICredentials = value; } } } /// /// Http返回参数类 /// public class HttpResult { /// /// Http请求返回的Cookie /// public string Cookie { get; set; } /// /// Cookie对象集合 /// public CookieCollection CookieCollection { get; set; } /// /// 返回的String类型数据 只有ResultType.String时才返回数据,其它情况为空 /// public string Html { get; set; } /// /// 返回的Byte数组 只有ResultType.Byte时才返回数据,其它情况为空 /// public byte[] ResultByte { get; set; } /// /// header对象 /// public WebHeaderCollection Header { get; set; } /// /// 返回状态说明 /// public string StatusDescription { get; set; } /// /// 返回状态码,默认为OK /// public HttpStatusCode StatusCode { get; set; } } /// /// 返回类型 /// public enum ResultType { /// /// 表示只返回字符串 只有Html有数据 /// String, /// /// 表示返回字符串和字节流 ResultByte和Html都有数据返回 /// Byte } /// /// Post的数据格式默认为string /// public enum PostDataType { /// /// 字符串类型,这时编码Encoding可不设置 /// String, /// /// Byte类型,需要设置PostdataByte参数的值编码Encoding可设置为空 /// Byte, /// /// 传文件,Postdata必须设置为文件的绝对路径,必须设置Encoding的值 /// FilePath } /// /// Cookie返回类型 /// public enum ResultCookieType { /// /// 只返回字符串类型的Cookie /// String, /// /// CookieCollection格式的Cookie集合同时也返回String类型的cookie /// CookieCollection } /// HttpHelper的2次封装函数 作者: /// public class MyHttpHelper { #region 公共函数 /// 返回 HTML 字符串的编码结果 /// 字符串 /// 编码结果 public static string HtmlEncode(string str) { if (string.IsNullOrEmpty(str)) { return ""; } return str.Length > 0 ? HttpUtility.HtmlEncode(str) : ""; } /// 返回 HTML 字符串的解码结果 /// 字符串 /// 解码结果 public static string HtmlDecode(string str) { if (string.IsNullOrEmpty(str)) { return ""; } return str.Length > 0 ? HttpUtility.HtmlDecode(str) : ""; } /// /// 根据指定的编码对RUl进行解码 /// /// 要解码的字符串 /// 要进行解码的编码方式 /// 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); } } /// 根据指定的编码对URL进行编码 /// 要编码的URL /// 要进行编码的编码方式 /// 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); } } /// /// 根据 charSet 返回 Encoding /// /// "gb2312" or "utf-8",默认: "" == "utf-8" /// 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 /// HTTP Get方式请求数据 /// URL /// user=123123 & pwd=1231313" /// "gb2312" or "utf-8",默认: "" == "utf-8" /// 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 /// HTTP Get方式请求数据 /// URL /// "gb2312" or "utf-8",默认: "" == "utf-8" /// 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 ""; } /// POST客服消息/summary> /// URL /// 内容 /// 消息状态 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 }
封装的JsonHelpers类如下
#region 通用 ///检查字符串是否json格式 /// /// 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; } /// 检查字符串是否json格式数组 /// /// public static bool IsJsonRs(string jText) { if (string.IsNullOrEmpty(jText) || jText.Length < 3) { return false; } if (jText.Substring(0, 3) == "[{\"") { return true; } return false; } /// 格式化 json /// /// public static string Fmt_Null(string jText) { return StringHelper.ReplaceString(jText, ":null,", ":\"\",", true); } /// 格式化 json ,删除左右二边的[] /// /// public static string Fmt_Rs(string jText) { jText = jText.Trim(); jText = jText.Trim('['); jText = jText.Trim(']'); return jText; } #endregion #region Json序列化 /// 序列化 /// object /// 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); } /// 序列化--sql /// DataTable /// public static string ToJson_FromSQL(DataTable dt) { string ss = ToJson(dt); dt.Dispose(); return ss; } #endregion #region Json反序列化 /// 反序列化 /// /// public static DataTable ToDataTable(string jText) { if (string.IsNullOrEmpty(jText)) { return null; } else { try { return JsonConvert.DeserializeObject (jText); } catch { return null; } } } /// 反序列化 /// 类型 /// json字符串 /// 类型数据 public static T ToObject (string jText) { return (T)JsonConvert.DeserializeObject(jText, typeof(T)); } #endregion
其中,如果是VS2015以下的,可以将url字符串改成string.format("")方式
调用取值的方式
点击公众号链接效果如下:
未完待续,持续填坑中。。。