1. 程式人生 > >C#後臺 Get、Post 網絡請求

C#後臺 Get、Post 網絡請求

urn lse bre 示例 之間 close 開始 encode b-

1.Post、Get請求

技術分享圖片
public static string HttpPost(string url, string param)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.Accept = "
*/*"; request.Timeout = 15000; request.AllowAutoRedirect = false; StreamWriter requestStream = null; WebResponse response = null; string responseStr = null; try { requestStream = new StreamWriter(request.GetRequestStream()); requestStream.Write(param); requestStream.Close(); response
= request.GetResponse(); if (response != null) { StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8); responseStr = reader.ReadToEnd(); reader.Close(); } }
catch (Exception) { throw; } finally { request = null; requestStream = null; response = null; } return responseStr; }
Post提交 技術分享圖片
public static string HttpPost(string url, string param)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.Accept = "*/*";
            request.Timeout = 15000;
            request.AllowAutoRedirect = false;

            StreamWriter requestStream = null;
            WebResponse response = null;
            string responseStr = null;

            try
            {
                requestStream = new StreamWriter(request.GetRequestStream());
                requestStream.Write(param);
                requestStream.Close();

                response = request.GetResponse();
                if (response != null)
                {
                    StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                    responseStr = reader.ReadToEnd();
                    reader.Close();
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                request = null;
                requestStream = null;
                response = null;
            }

            return responseStr;
        }
Get提交

微信公眾平臺調用post提交數據 有些需要傳遞json格式的數據如果不是json格式的數據可能會報錯

2.簡單的示例代碼

技術分享圖片
/// <summary>
        /// 將字典類型序列化為json字符串
        /// </summary>
        /// <typeparam name="TKey">字典key</typeparam>
        /// <typeparam name="TValue">字典value</typeparam>
        /// <param name="dict">要序列化的字典數據</param>
        /// <returns>json字符串</returns>
        public static string SerializeDictionaryToJsonString<TKey, TValue>(Dictionary<TKey, TValue> dict)
        {
            if (dict.Count == 0)
                return "";

            string jsonStr = JsonConvert.SerializeObject(dict);
            return jsonStr;
        }
簡單的將字典類型序列化為json字符串 技術分享圖片
public ActionResult Index()
{
            Dictionary<string, string> list = new Dictionary<string, string>();
            list.Add("begin_date", "2014-12-07");
            list.Add("end_date", "2014-12-07");
            //用戶分析數據接口  開始沒有傳遞json格式的數據 總是報日期格式不正確 簡單的寫了個json轉換的
            var str = Utils.HttpPost("https://api.weixin.qq.com/datacube/getusersummary?access_token=xxxxxxxx", SerializeDictionaryToJsonString(list));

            return View();
}    
用戶分析數據接口

3.獲取網頁信息--可以做到一個文件多出使用(後臺結果公告內容,通過獲取結果公告內容抓取到前臺顯示)

技術分享圖片
#region 獲取網頁信息
        #region 根據URL地址獲取信息GET

        public static String GetResult(string url)
        {
            return GetResult(url, Encoding.Default);
        }
        #endregion

        #region 根據URL地址獲取對應編碼信息
        public static String GetResult(string url, Encoding encoding)
        {
            try
            {

                var webRequest = (HttpWebRequest)WebRequest.Create(url);
                //獲取響應結果 
                var webResponse = (HttpWebResponse)webRequest.GetResponse();
                //獲取響應流
                Stream stream = webResponse.GetResponseStream();
                using (StreamReader streamReader = new StreamReader(stream, encoding))
                {
                    string result = String.Empty;
                    result = streamReader.ReadToEnd();
                    streamReader.Close();
                    webResponse.Close();
                    webRequest.Abort();
                    return result;
                }
            }
            catch (Exception ex)
            {
                return "-1";
                //return ex.Message.Length > 100 ? ex.Message.Substring(0, 100) : ex.Message; 
            }
        }
        #endregion
        #endregion
獲取網頁信息 技術分享圖片
/// <summary>
    /// 獲取並截取HTML源碼
    /// </summary>
    /// <param name="strUrl"></param>
    /// <returns></returns>
    public static string GetUrlAndCutSourceHtml(string strUrl)
    { 
        string strTemp = Common.GetResult(strUrl, System.Text.Encoding.GetEncoding("utf-8"));
        if (!strTemp.Equals("-1"))
        {
            strTemp = strTemp.Substring(strTemp.IndexOf("<!--begin-->"));
            strTemp = strTemp.Substring(0, strTemp.IndexOf("<!--end-->"));
        }
        return strTemp;
    }
獲取之間的內容 技術分享圖片
<body>
    <form>
        <!--begin-->
        <div>
            顯示的內容
            顯示的內容
            顯示的內容
            顯示的內容
            顯示的內容
            顯示的內容
            顯示的內容
            顯示的內容
            顯示的內容
            顯示的內容
            顯示的內容
        </div>
        <!--end-->
    </form>
</body>
</html>
html頁面

C#後臺 Get、Post 網絡請求