/// <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)); } }
/// <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)); } }
/// <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>(); bool urlQuery = option.IsMustQueryString(); string requestUrl = option.Url; if (option.Data != null && urlQuery) //GET 请求,需要将参数合并到URL,形成查询字符串参数 { if (option.Url.IndexOf('?') < 0) { requestUrl = option.Url + "?" + GetQueryString(option.Data); } else { requestUrl = option.Url + "&" + GetQueryString(option.Data); } } HttpWebRequest request = client.CreateWebRequest(requestUrl); SetWebRequest(request, option); option.SetRequestAction?.Invoke(request); // 调用委托 if (option.Data != null && urlQuery == false) // POST提交数据 { await client.SetRequestDataAsync(option.Data, option.Format); } using (HttpWebResponse response = await client.GetResponseAsync()) { option.ReadResponseAction?.Invoke(response); // 调用委托 return(client.GetResult <T>(response)); } }