Esempio n. 1
0
        /// <summary>
        /// 发送Http请求,模拟访问指定的Url,返回响应内容
        /// </summary>
        /// <param name="serviceUrl">要访问的Url</param>
        /// <param name="requestData">请求体(若为GetMethod时,则该值应为空)</param>
        /// <param name="requestHeaders">请求头</param>
        /// <param name="requestMethod">请求方式</param>
        /// <param name="contentType"></param>
        /// <returns>响应内容(响应头、响应体)</returns>
        public JObject Request(string serviceUrl, string requestData, Dictionary <string, string> requestHeaders = null, RequestMethod requestMethod = RequestMethod.POST, string contentType = "")
        {
            string retString = null;
            var    url       = serviceUrl;

            if (!string.IsNullOrEmpty(_baseUrl))
            {
                if (!_baseUrl.EndsWith("/") && !serviceUrl.StartsWith("/"))
                {
                    serviceUrl = $"/{serviceUrl}";
                }
                url = $"{_baseUrl}{serviceUrl}";
            }
            using (var response = GetHttpWebResponse(requestHeaders, requestData, url, requestMethod.As <string>(), contentType))
            {
                using (var myResponseStream = response.GetResponseStream())
                {
                    if (myResponseStream == null)
                    {
                        throw new InvalidOperationException();
                    }
                    var myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
                    retString = myStreamReader.ReadToEnd();
                    myStreamReader.Close();
                    myResponseStream.Close();
                    myStreamReader = null;
                }
            }
            var jResult = JObject.Parse(retString);

            return(jResult);
        }