【C#网络基础】C# get post请求

using KTCommon.Helper;
using KTCommon.LOG;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace KTCommon.HTTP
{
    public class KTHttpRequest
    {
        #region GET请求

        /// <summary>
        /// GET请求
        /// </summary>
        /// <param name="nUrl"></param>
        /// <param name="nCacheSecond"></param>
        /// <returns></returns>
        public static string _Get(string nUrl, int nCacheSecond = 0)
        {
            try
            {
                string cacheKey = "";
                TraceLog.m_Trace.Trace("_Get Request Url=" + nUrl);

                if (nCacheSecond > 0)
                {
                    if (nUrl.Contains("&signature="))
                    {
                        string temp = nUrl.Substring(0, nUrl.IndexOf("&signature="));
                        cacheKey = MyMD5Helper.GetMD532(temp).ToUpper();
                    }
                    else
                    {
                        cacheKey = MyMD5Helper.GetMD532(nUrl).ToUpper();
                    }
                    
                    var cache = CacheHelper.Get(cacheKey);
                    if (null != cache)
                    {
                        TraceLog.m_Trace.Trace(cacheKey + " read cache...");
                        return cache as string;
                    }
                }

                string htmltext = "";
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(nUrl);

                // 头信息
                myRequest.Headers.Add("Cache-Control", "no-cache");
                myRequest.Method = "GET";

                myRequest.ContentType = "text/plain";
                // 发送的数据信息 
                myRequest.Timeout = 15 * 1000;

                HttpWebResponse response = (HttpWebResponse)myRequest.GetResponse();
                Stream responseStream = response.GetResponseStream();
                StreamReader sr = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
                htmltext = sr.ReadToEnd();
                sr.Close();
                sr.Dispose();
                responseStream.Close();
                TraceLog.m_Trace.Trace("_Get htmltext=" + htmltext);

                if (nCacheSecond > 0 && htmltext.StartsWith("{\"code\":0,"))
                {
                    TraceLog.m_Trace.Trace(cacheKey + " wrrite cache...");
                    CacheHelper.Insert(cacheKey, htmltext, nCacheSecond);
                }

                return htmltext;
            }
            catch (Exception ex)
            {
                TraceLog.m_Trace.Trace("_Get Exception=" + ex);
                return "";
            }

        }

        #endregion

        #region POST请求

        /// <summary>
        /// POST请求
        /// </summary>
        /// <param name="nUrl"></param>
        /// <param name="nMethodName"></param>
        /// <param name="nPostData"></param>
        /// <returns></returns>
        public static string _Post(string nUrl, string nMethodName, object nPostData, bool IsCache = false)
        {
#if DEBUG
            //urlAddress = "http://localhost/airwaykeeper/v1/API/API2WShare.aspx";
            //strMethodName = "_GetShareInfoByUID";
            //strRequest = File.ReadAllText("d:\\request.txt", Encoding.UTF8);
#endif
            string htmltext = "";
            string cacheKey = "";
            Byte[] bSend = null;
            try
            {
                string postData = Newtonsoft.Json.JsonConvert.SerializeObject(nPostData);
                TraceLog.m_Trace.Trace(nMethodName + " RequestUrl=" + nUrl);
                TraceLog.m_Trace.Trace(nMethodName + " PostData=" + postData);

                //缓存
                if (IsCache)
                {
                    cacheKey = nMethodName + "-" + MyMD5Helper.GetMD532(nUrl + nMethodName + postData).ToUpper();
                    var cache = CacheHelper.Get(cacheKey);
                    if (null != cache)
                    {
                        TraceLog.m_Trace.Trace(cacheKey + " read cache...");
                        return cache as string;
                    }
                }

                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(nUrl);

                // 头信息
                myRequest.Headers.Add("Cache-Control", "no-cache");
                myRequest.Headers.Add("MethodName", nMethodName);
                myRequest.Method = "POST";

                myRequest.ContentType = "application/json";
                // 发送的数据信息 
                bSend = Encoding.UTF8.GetBytes(postData);
                myRequest.ContentLength = bSend.Length;
                myRequest.Timeout = 60 * 1000;

                // 发送数据 
                Stream newStream = myRequest.GetRequestStream();
                newStream.Write(bSend, 0, bSend.Length);
                newStream.Close();

                HttpWebResponse response = (HttpWebResponse)myRequest.GetResponse();
                Stream responseStream = response.GetResponseStream();
                StreamReader sr = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
                htmltext = sr.ReadToEnd();
                sr.Close();
                sr.Dispose();
                responseStream.Close();
            }
            catch (Exception ex)
            {
                TraceLog.m_Trace.Trace(nMethodName + " Exception=" + ex.ToString());
                return new BaseResponse(ex.Message).ToString();
            }
            TraceLog.m_Trace.Trace(nMethodName + " ResponseJson=" + htmltext);

            //缓存
            if (IsCache)
            {
                if (htmltext.Contains("IsSuccess\":true,"))
                {
                    TraceLog.m_Trace.Trace(cacheKey + " wrrite cache...");
                    CacheHelper.Max(cacheKey, htmltext);
                }
            }

            return htmltext;
        }

        #endregion
    }

    public class BaseResponse
    {
        public BaseResponse(string tmp)
        {

        }

        public override string ToString()
        {
            return "";
        }
    }
}

 

posted @ 2016-09-27 11:20  0539  阅读(355)  评论(0编辑  收藏  举报