若是用戶在微信客戶端中訪問第三方網頁,公衆號能夠經過微信網頁受權機制,來獲取用戶基本信息,進而實現業務邏輯。html
注意:網頁受權兩種方式sql
更多網頁受權請查閱官網文檔:網頁受權數據庫
靜默受權便可以在用戶關注的的時候,獲取用戶基本信息,此過程用戶無感知。json
第一步,經過工廠類 轉發請求api
/// <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; }
第二步,寫用戶關注事件數組
/// <summary> /// 用戶關注 /// </summary> /// <param name="em"></param> /// <returns></returns> 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,便可獲取用戶基本信息(此處演示是將該用戶存入數據庫中)瀏覽器
/// <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; }
順便提下上文中用到的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 = $"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<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 = $"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方法
/// <summary> //用戶受權以後,獲取受權的Access_Token與基本的Access_Token是不一樣的(推薦方法) /// </summary> /// <param name="code">用戶受權以後的Code</param> /// <returns></returns> 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<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 }
封裝的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
其中,若是是VS2015如下的,能夠將url字符串改爲string.format("")方式
調用取值的方式
點擊公衆號連接效果以下:
未完待續,持續填坑中。。。