客戶端 post ,get 訪問伺服器

程式園丁發表於2018-07-20
 private void sendReuestExpansion()
    {
        HttpRequest<T> req = this;
        HttpWebRequest request;
        try
        {
            byte[] data = new byte[] { };
            if (req.PostData != null)
            {
                //HttpMethodEnum httpMethodEnum = (HttpMethodEnum)Enum.Parse(typeof(HttpMethodEnum), req.HttpMethod.ToString());
                switch (req.HttpMethod)
                {
                    case HttpMethodEnum.Get:
                        req.Url = req.Url.Contains("?") ? req.Url : (req.Url + "?");
                        foreach (var item in req.PostData.GetType().GetProperties())
                        {
                            var temp = item.GetValue(req.PostData, null);
                            if (temp != null)
                            {
                                temp = System.Web.HttpUtility.UrlEncode(Convert.ToString(temp));
                            }
                            req.Url += item.Name + "=" + temp + "&";
                        }
                        req.Url = req.Url.TrimEnd(`&`);
                        break;

                    case HttpMethodEnum.Post:
                        var str = (req.PostData.GetType().Name.ToLower() == "string") ? Convert.ToString(req.PostData) : JsonConvert.SerializeObject(req.PostData);
                        data = Encoding.UTF8.GetBytes(str);
                        break;

                    default:
                        break;
                }
            }
            Uri uri = new Uri(req.Url);
            request = (HttpWebRequest)WebRequest.Create(uri);
            request.Timeout = 150000;
            request.Method = req.HttpMethod.ToString().ToUpper();
            request.ContentType = "application/json; charset=utf-8";

            #region 【KeepAlive】
            /*
             HttpWebRequest的KeepAlive預設是true,如果使用的時候僅僅只是關閉流,不關閉網路卡上的通道的話,第二個請求在TCP沒有關閉的情況下是走同一個通道,此時本機的TCP通道就會拋異常出來,這是本機拋的錯誤。
             所以除了關閉本機的IO資源外,還要關閉網路資源。需要把KeepAlive設定成false就可以了。TCP通訊結束後會自動關閉該請求所使用的通道。
             request.About() 是發現異常就斷掉http是上層協議,底層還是走tcp的,如果不關閉的話,第二個http會預設走沒有關閉的tcp。
             如果有併發的時候,資料就亂了。所以應該及時關閉tcp,每次開一個新埠。 
             */
            request.KeepAlive = false;
            #endregion

            if (data != null && data.Length > 0)
            {
                request.ContentLength = data.Length;
                Stream sm = request.GetRequestStream();
                sm.Write(data, 0, data.Length);
                sm.Flush();
                sm.Close();
            }

            StringBuilder sb = new StringBuilder("");
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream streamResponse = response.GetResponseStream();
            StreamReader streamRead = new StreamReader(streamResponse, Encoding.UTF8);
            Char[] readBuff = new Char[256];
            int count = streamRead.Read(readBuff, 0, 256);
            while (count > 0)
            {
                String outputData = new String(readBuff, 0, count);
                sb.Append(outputData);
                count = streamRead.Read(readBuff, 0, 256);
            }
            streamResponse.Close();
            streamRead.Close();

            if (response != null)
            {
                response.Close();
                response = null;
            }
            #region 【HttpWebRequest 請求釋放】
            if (request != null)
            {
                request.Abort();
                request = null;
            }
            #endregion

            if (!String.IsNullOrEmpty(sb.ToString()))
            {
                resultData = HttpResult<T>.ToHttpResultByJosn(sb.ToString()); //sb.ToHttpResult<T>();
            }
            else
            { }
        }
        catch (Exception ex)
        {
            resultData = HttpResult<T>.ToHttpFaildResult(ex.Message);
        }

    }

 

相關文章