Exemple #1
0
        /// <summary>
        /// 根据指定的HttpOption参数,用【异步】方式发起一次HTTP请求
        /// </summary>
        /// <typeparam name="T">返回值的类型参数</typeparam>
        /// <param name="option">HttpOption的实例,用于描述请求参数</param>
        /// <returns>返回服务端的调用结果,并转换成指定的类型</returns>
        public async static Task <T> SendAsync <T>(this HttpOption option)
        {
            if (option == null)
            {
                throw new ArgumentNullException("option");
            }

            option.CheckInput();

            HttpClient client = ObjectFactory.New <HttpClient>();

            // 获取实际请求址,并创建 HttpWebRequest 实例
            string         requestUrl = option.GetRequestUrl();
            HttpWebRequest request    = client.CreateWebRequest(requestUrl);

            SetWebRequest(request, option);

            option.SetRequestAction?.Invoke(request);                   // 调用委托

            // 触发发送前事件
            client.ExecuteBeforeSendRequestEvent();

            // 设置提交数据
            await client.SetRequestDataAsync(option.GetPostData(), option.Format);

            using (HttpWebResponse response = await client.GetResponseAsync()) {
                option.ReadResponseAction?.Invoke(response);                    // 调用委托

                return(client.GetResult <T>(response));
            }
        }
Exemple #2
0
        /// <summary>
        /// 根据指定的HttpOption参数,用【同步】方式发起一次HTTP请求
        /// </summary>
        /// <typeparam name="T">返回值的类型参数</typeparam>
        /// <param name="option">HttpOption的实例,用于描述请求参数</param>
        /// <returns>返回服务端的调用结果,并转换成指定的类型</returns>
        public static T Send <T>(this HttpOption option)
        {
            if (option == null)
            {
                throw new ArgumentNullException("option");
            }

            option.CheckInput();

            HttpClient client = ObjectFactory.New <HttpClient>();

            // 获取实际请求址,并创建 HttpWebRequest 实例
            string         requestUrl = option.GetRequestUrl();
            HttpWebRequest request    = client.CreateWebRequest(requestUrl);

            // 设置HttpWebRequest请求头之类的属性
            SetWebRequest(request, option);

            option.SetRequestAction?.Invoke(request);                           // 调用委托

            // 设置提交数据
            client.SetRequestData(option.GetPostData(), option.Format);

            using (HttpWebResponse response = client.GetResponse()) {
                option.ReadResponseAction?.Invoke(response);                    // 调用委托

                return(client.GetResult <T>(response));
            }
        }