HttpRequest Sample

  • 577
  • 0
  • 2015-12-28

摘要:[.NET][C#] HttpRequest Sample

* 呼叫類別中所提供的方法, 發出Http Request並回傳指定物件

1. Class


    public class Connector
    {
        /// <summary>
        /// WebRequest
        /// </summary>
        private WebRequest _req;

        /// <summary>
        /// 建構子
        /// </summary>
        private Connector()
        {
        }
                
        /// <summary>
        /// 初始化Connetcor
        /// </summary>
        /// <param name="url">HttpRequest的URL</param>
        /// <param name="headers">Headers, 預設是null</param>
        /// <param name="contentType">contentType, 預設是application/json</param>
        /// <param name="timeout">Request的Timeout時間, 預設是5秒</param>
        /// <returns>Connector實例</returns>
        public static Connector Create(string url, Dictionary<string, string> headers = null, string contentType = "application/json", int timeout = 50000)
        {
            Connector currentReq = new Connector();

            currentReq._req = HttpWebRequest.Create(url);
            currentReq._req.Timeout = timeout;
            currentReq._req.ContentType = contentType;
            if (headers != null)
            {
                foreach (var hd in headers)
                {
                    currentReq._req.Headers.Add(hd.Key, hd.Value);
                }
            }

            return currentReq;
        }

        /// <summary>
        /// GET
        /// </summary>
        /// <typeparam name="T">回傳物件型別</typeparam>
        /// <returns>回傳物件</returns>
        public T Get<T>()
        {
            _req.Method = "GET";

            string responseString = GetResponseString();

            JavaScriptSerializer js = new JavaScriptSerializer();
            T data = js.Deserialize<T>(responseString);

            return data;
        }

        /// <summary>
        /// POST
        /// </summary>
        /// <typeparam name="T">回傳物件型別</typeparam>
        /// <param name="postData">傳出資料內容</param>
        /// <returns>回傳物件</returns>
        public T Post<T>(object postData)
        {
            _req.Method = "POST";

            JavaScriptSerializer js = new JavaScriptSerializer();
            string serialStr = js.Serialize(postData);
            using (Stream streamOut = _req.GetRequestStream())
            {
                using (StreamWriter sw = new StreamWriter(streamOut))
                {
                    sw.Write(serialStr);
                }
            }
            
            string responseString = GetResponseString();
            T data = js.Deserialize<T>(responseString);

            return data;
        }

        /// <summary>
        /// 發出Http請求
        /// </summary>
        /// <returns>Http請求回傳的字串</returns>
        private string GetResponseString()
        {
            Stream s = _req.GetResponse().GetResponseStream();
            StreamReader sr = new StreamReader(s);
            string str = sr.ReadToEnd();
            sr.Close();
            sr.Dispose();
            s.Close();
            s.Dispose();

            return str;
        }        
    }

 

2. use


ResponseContent response = Connector.Create("http://localhost:1199/MemberShip/Register").Post<ResponseContent>(userInfo);