.net post提交和獲得html頁面的原始碼

【驀然回首】發表於2018-03-05
/// <summary>
        /// 獲得頁面的html原始碼  主要用於後臺生成靜態檔案時獲得原始碼
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string GetPageHTML(string url)
        {
            string httpString = string.Empty;
            WebRequest request = WebRequest.Create(url);
            request.Timeout = 200000;            
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                if (response.StatusDescription.ToLower().Equals("ok"))
                {
                    using (StreamReader writer = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("GB2312")))
                    {
                        httpString = writer.ReadToEnd();
                    }
                }
            }
            return httpString;
        }
 
 
        /// <summary>
        /// 獲得頁面的html原始碼  主要用於後臺生成靜態檔案時獲得原始碼UTF-8
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string GetPageHTMLUTF8(string url)
        {
            string httpString = string.Empty;
            WebRequest request = WebRequest.Create(url);
            request.Timeout = 200000;            
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                if (response.StatusDescription.ToLower().Equals("ok"))
                {
                    using (StreamReader writer = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("UTF-8")))
                    {
                        httpString = writer.ReadToEnd();
                    }
                }
            }
            return httpString;
        }
 
 
        /// <summary>
        /// post提交JSON資料。支援.net4.0及以下的版本
        /// </summary>
        /// <param name="url"></param>
        /// <param name="json"></param>
        /// <returns></returns>
        public static string GetHtmlByJson(string url, string json = "")
        {
            var result = string.Empty;
 
            try
            {
                var request = WebRequest.Create(url) as HttpWebRequest;
                request.ContentType = "text/json";
                request.Method = "post";
                //request.CookieContainer = _cookie;
 
                using (var streamWriter = new StreamWriter(request.GetRequestStream()))
                {
                    streamWriter.Write(json);
                    streamWriter.Flush();
                    streamWriter.Close();
 
                    var response = (HttpWebResponse)request.GetResponse();
 
                    using (var reader = new StreamReader(response.GetResponseStream()))
                    {
                        result = reader.ReadToEnd();
                    }
                }
            }
            catch (UriFormatException uex)
            {
                // 出錯處理
            }
 
            return result;
        }
 
        /// <summary> 
        /// 利用WebClient 遠端POST資料並返回資料 
        /// </summary> 
        /// <param name="strUrl">遠端URL地址</param> 
        /// <param name="strParams">引數,要提交的JSON字串</param> 
        /// <param name="RespEncode">POST資料的編碼</param> 
        /// <param name="ReqEncode">獲取資料的編碼</param> 
        /// <returns></returns> 
        public static string PostData(string strUrl, string strParams, Encoding RespEncode, Encoding ReqEncode)
        {
            /**
             * 本函式只支援.net4.5以上的框架
            HttpClient httpclient = new HttpClient();
            try
            {
                //開啟頁面 
                httpclient.Credentials = CredentialCache.DefaultCredentials;
                //從指定的URI下載資源 
                byte[] responseData = httpclient.DownloadData(strUrl);
                string srcString = RespEncode.GetString(responseData);
 
                httpclient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
                string postString = strParams;
                // 將字串轉換成位元組陣列 
                byte[] postData = Encoding.ASCII.GetBytes(postString);
                // 上傳資料,返回頁面的位元組陣列 
                responseData = httpclient.UploadData(strUrl, "POST", postData);
                srcString = ReqEncode.GetString(responseData);
 
                return srcString;
            }
            catch (Exception ex)
            {
                //記錄異常日誌 
                //釋放資源 
                httpclient.Dispose();
                return string.Empty;
            }
            */
            return "";
        }
 
 
        /// <summary>
        /// 執行POST提交範例
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postdata">"LoginName=365admin&Password=fob123"</param>
        /// <returns></returns>
        public static string PostPageHTMLUTF8(string url, string postdata)
        {
            WebClient client = new WebClient();
            System.Collections.Specialized.NameValueCollection list = new System.Collections.Specialized.NameValueCollection();            
            list.Add("opencheckindatatype""3");
            list.Add("starttime""1492617600");
            list.Add("endtime""1492790400");
            // "useridlist": ["james","paul"]              
            list.Add("useridlist""['TuHuaXing']");            
            byte[] j = client.UploadValues(url, list);
            //var dec = BitConverter.ToInt64(j,0);
            //string jS = BitConverter.ToString(j);
            //jS = Convert.ToString(jS,10);
            return System.Text.Encoding.Default.GetString(j);
 
            //目標頁面獲取值   request.form["id"]
 
            /**
            WebRequest request7 = WebRequest.Create(url);
            request7.Method = "POST";
 
            //post傳引數            
            byte[] bytes = Encoding.ASCII.GetBytes(postdata);
            request7.ContentType = "application/x-www-form-urlencoded";
            request7.ContentLength = postdata.Length;
            request7.S
            Stream sendStream = request7.GetRequestStream();
            sendStream.Write(bytes, 0, bytes.Length);
            sendStream.Close();
 
            //得到返回值  
            WebResponse response7 = request7.GetResponse();
            string OrderQuantity = new StreamReader(response7.GetResponseStream(), Encoding.GetEncoding("utf-8")).ReadToEnd();
            return OrderQuantity;
            //轉化成json物件處理
            //List<GetOrderQuantity> getOrderQuantity = sr.Deserialize<List<GetOrderQuantity>>(OrderQuantity);            **/
        }

相關文章