|
/// <summary>
/// http 请求工具类
/// </summary>
public static class RequestUtils
{
#region 获取Url来自参数集合
/// <summary>
/// 获取Url来自参数集合
/// </summary>
/// <param name="parameters"></param>
/// <returns></returns>
public static string GetParams(IDictionary<string, object> parameters)
{
StringBuilder builder = new StringBuilder();
foreach (var key in parameters.Keys)
{
string name = key;
object parm = parameters[key];
string valu = (parm == null ? "null" : parm.ToString());
if (builder.Length > 0)
builder.Append("&");
builder.AppendFormat("{0}={1}", System.Web.HttpUtility.UrlEncode(name), System.Web.HttpUtility.UrlEncode(valu));
}
return builder.ToString();
}
#endregion
/// <summary>
///
/// </summary>
/// <param name="baseUrl"></param>
/// <param name="parameters"></param>
/// <returns></returns>
public static async Task<string> InvokeAsync(string baseUrl, IDictionary<string, object> parameters)
{
var url = baseUrl + "?" + RequestUtils.GetParams(parameters);
var request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Method = "GET";
using (var response = await request.GetResponseAsync())
{
return Encoding.UTF8.GetString(await response.ReceiveAsync());
}
}
/// <summary>
///
/// </summary>
/// <param name="baseUrl"></param>
/// <param name="parameters"></param>
/// <returns></returns>
public static string Invoke(string baseUrl, IDictionary<string, object> parameters)
{
var url = baseUrl + "?" + RequestUtils.GetParams(parameters);
var request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Method = "GET";
using (var response = request.GetResponse())
{
return Encoding.UTF8.GetString(response.Receive());
}
}
}
internal static class WebResponseExtensions
{
/// <summary>
/// 读取数据
/// </summary>
/// <param name="response"></param>
/// <returns></returns>
public static byte[] Receive(this WebResponse response)
{
if (response == null)
return null;
var contentEncoding = response.Headers[HttpResponseHeader.ContentEncoding];
if (!string.IsNullOrEmpty(contentEncoding)
&& contentEncoding.ToLower() == "gzip")
{
using (var responseStream = response.GetResponseStream())
{
return responseStream.GZipDecompress();
}
}
using (var responseStream = response.GetResponseStream())
{
return responseStream.ReadAllBytes();
}
}
/// <summary>
/// 读取数据
/// </summary>
/// <param name="response"></param>
/// <returns></returns>
public static async Task<byte[]> ReceiveAsync(this WebResponse response)
{
if (response == null)
return null;
var contentEncoding = response.Headers[HttpResponseHeader.ContentEncoding];
if (!string.IsNullOrEmpty(contentEncoding)
&& contentEncoding.ToLower() == "gzip")
{
using (var responseStream = response.GetResponseStream())
{
return await responseStream.GZipDecompressAsync();
}
}
using (var responseStream = response.GetResponseStream())
{
return await responseStream.ReadAllBytesAsync();
}
}
}
|
|