勤学如春起之苗不见其增日有所长,辍学如磨刀之石不见其损日有所亏

 

     /// <summary>
        /// Post接口方法
        /// </summary>
        /// <param name="requestUri"></param>
        /// <param name="json"></param>
        /// <returns></returns>
        public static string PostHttpRequest(string requestUri, string json, IDbSqlService dbSqlService, Int32 time = 7000, string version = "1.0")
        {
            DateTime requestDate = DateTime.Now;
            DateTime respondeDate;
            TimeSpan ts;

            //json格式请求数据
            string requestData = json;
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(requestUri);
            //utf-8编码
            byte[] buf = System.Text.Encoding.GetEncoding("utf-8").GetBytes(requestData);

            //post请求
            myRequest.Method = "POST";
            myRequest.ContentLength = buf.Length;
            myRequest.MaximumAutomaticRedirections = 1;
            myRequest.Headers.Add("Api-Version", version);
            myRequest.AllowAutoRedirect = true;
            myRequest.Timeout = time;

            myRequest.ContentType = "application/json; charset=utf-8";
            myRequest.Accept = "application/json";
            try
            {
                Stream newStream = myRequest.GetRequestStream();
                newStream.Write(buf, 0, buf.Length);
                newStream.Close();

                string ReqResult = string.Empty;
                HttpWebResponse myResponse = null;

                myResponse = (HttpWebResponse)myRequest.GetResponse();
                respondeDate = DateTime.Now;
                ts = respondeDate.Subtract(requestDate);
                StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
                ReqResult = reader.ReadToEnd();
                reader.Close();
                myResponse.Close();
                InsertLog(requestDate, respondeDate, ts, json, requestUri, myResponse.Method, myResponse.StatusCode.ToString(), ReqResult, dbSqlService);
                return ReqResult;
            }
            catch (Exception ex)
            {
                respondeDate = DateTime.Now;
                ts = respondeDate.Subtract(requestDate);
                InsertLog(requestDate, respondeDate, ts, ex.Message, requestUri, "Post", "Exception", "", dbSqlService);
                return ex.Message;
            }


        }
posted on 2018-06-22 11:29  TheClound  阅读(410)  评论(0编辑  收藏  举报