Пример #1
0
        /// <summary>
        /// Post方式提交数据
        /// </summary>
        /// <param name="url"></param>
        /// <param name="json"></param>
        /// <returns></returns>
        public static string PostData(string url, string json, ref APIExecuteStatistics data, Dictionary <string, string> customHeaders)
        {
            string result = "";

            data.BytesSent = data.BytesReceived = 0;
            Stopwatch watch = new Stopwatch();

            watch.Start();
            try
            {
                string         strURL  = url;
                HttpWebRequest request = GetWebRequest(url, "POST");
                request.ContentType = "application/json;charset=UTF-8";
                if (customHeaders != null && customHeaders.Count > 0)
                {
                    foreach (var item in customHeaders)
                    {
                        request.Headers.Add(item.Key, System.Web.HttpUtility.UrlEncode(item.Value, Encoding.UTF8));
                    }
                }
                byte[] payload = Encoding.UTF8.GetBytes(json);
                //if (SupportGZip)
                //{
                //    payload = HttpExtension.Compress(payload);
                //}
                using (Stream writer = request.GetRequestStream())
                {
                    writer.Write(payload, 0, payload.Length);
                    writer.Close();
                    data.BytesSent += request.GetRequestLength();
                    SentBytes      += data.BytesSent;
                    LastSentBytes  += data.BytesSent;
                    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                    {
                        Encoding encoding = GetEncoding(response);
                        result              = GetResponseAsString(response, encoding, ref data);
                        data.BytesReceived += response.GetResponseLength();
                        ReceivedBytes      += data.BytesReceived;
                        LastReceivedBytes  += data.BytesReceived;
                    }
                }
            }
            catch (Exception e)
            {
                data.Exception = e;
                string       message      = e.Message;
                WebException webException = e as WebException;
                if (webException != null)
                {
                    try
                    {
                        HttpWebResponse response = webException.Response as HttpWebResponse;
                        Encoding        encoding = GetEncoding(response);
                        string          body     = GetResponseAsString(response, encoding, ref data);
                        message            += Environment.NewLine + "服务返回:" + body;
                        data.BytesReceived += response.GetResponseLength();
                        ReceivedBytes      += data.BytesReceived;
                        LastReceivedBytes  += data.BytesReceived;
                    }
                    catch { }
                }
                if (Debugger.IsAttached)
                {
                    message += Environment.NewLine + e.StackTrace.ToString();
                }
                result = GetJson(new ErrorWMSResponse {
                    Code = e.Message, Message = message
                });
            }
            watch.Stop();
            data.NetworkElapseTime = watch.ElapsedMilliseconds;
            return(result);
        }
Пример #2
0
        /// <summary>
        /// 把响应流转换为文本。
        /// </summary>
        /// <param name="rsp">响应流对象</param>
        /// <param name="encoding">编码方式</param>
        /// <returns>响应文本</returns>
        public static string GetResponseAsString(HttpWebResponse rsp, Encoding encoding, ref APIExecuteStatistics data)
        {
            Stream       stream = null;
            StreamReader reader = null;

            try
            {
                // 以字符流的方式读取HTTP响应
                stream = rsp.GetResponseStream();
                byte[] buffer = Read2Buffer(stream);
                data.BytesReceived += buffer.Length;
                ReceivedBytes      += buffer.Length;
                LastReceivedBytes  += buffer.Length;
                bool gzip = (rsp.ContentEncoding ?? "").ToLower().Contains("gzip");
                SupportGZip = gzip;
                if (gzip)
                {
                    byte[] newBuffer = HttpExtension.Decompress(buffer);
                    return(encoding.GetString(newBuffer, 0, newBuffer.Length));
                }
                else
                {
                    return(encoding.GetString(buffer, 0, buffer.Length));
                }
            }
            finally
            {
                // 释放资源
                if (reader != null)
                {
                    reader.Close();
                }
                if (stream != null)
                {
                    stream.Close();
                }
                if (rsp != null)
                {
                    rsp.Close();
                }
            }
        }
Пример #3
0
        private T PrivateExecute <T>(string url, IWMSRequest <T> request, Dictionary <string, string> customHeaders = null) where T : WMSResponse
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }
            if (string.IsNullOrWhiteSpace(url))
            {
                T response = ToObject <T>(GetJson(new ErrorWMSResponse {
                    Code = ErrorCodeMessage.ServiceAddressNotFound, Message = ErrorCodeMessage.ServiceAddressNotFoundMessage
                }));
                return(response);
            }
            APIExecuteStatistics data = new APIExecuteStatistics();

            data.StartTime      = DateTime.Now /*仅用于统计耗时,可以使用DateTime.Now*/;
            data.ServiceAddress = url;
            data.APIPath        = request.GetAPIPath();
            url               = url.TrimEnd('/') + "/" + request.GetAPIPath().TrimStart('/');
            data.FullURL      = url;
            data.RequestType  = request == null ? null : request.GetType();
            data.ResponseType = typeof(T);
            T resp = null;

            try
            {
                if (customHeaders == null)
                {
                    customHeaders = new Dictionary <string, string>();
                }
                foreach (var item in Properties)
                {
                    customHeaders.Add(item.Key, item.Value);
                }
                int currentMinute = DateTime.Now.Minute /*仅记录当前分钟数,可以使用DateTime.Now*/;
                if (lastMinute != currentMinute)
                {
                    //lastMinute = currentMinute;
                    //customHeaders["statistics-IP"] = ComputerHelper.GetIPAddress();
                }
                //lock (_bytesLocker)
                //{
                //    customHeaders["statistics-LastBytesSent"] = LastSentBytes.ToString("F0");
                //    customHeaders["statistics-LastBytesReceived"] = LastReceivedBytes.ToString("F0");
                //    LastSentBytes = LastReceivedBytes = 0;
                //}
                //customHeaders["statistics-BytesSent"] = SentBytes.ToString("F0");
                //customHeaders["statistics-BytesReceived"] = ReceivedBytes.ToString("F0");
                string json = GetJson(request);
                data.RequestContent = json;
                string response = PostData(url, json, ref data, customHeaders);
                data.ResponseContent = response;
                if (string.IsNullOrEmpty(response) || response.Trim().Length < 1)
                {
                    resp = ToObject <T>(GetJson(new ErrorWMSResponse {
                        Code = ErrorCodeMessage.EmptyResponse, Message = ErrorCodeMessage.EmptyResponseMessage
                    }));
                }
                else
                {
                    resp = ToObject <T>(response);
                }
                resp.Body        = response;
                resp.RequestJson = json;
                data.EndTime     = DateTime.Now /*仅用于统计耗时,可以使用DateTime.Now*/;
                data.ElapseTime  = (long)(data.EndTime - data.StartTime).TotalMilliseconds;
                data.Code        = resp.Code;
            }
            catch (Exception ex)
            {
                data.Exception = ex;
                throw ex;
            }
            finally
            {
                OnAPIExecuted(new APIExecutedEventArgs {
                    Data = data
                });
            }
            return(resp);
        }