using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
namespace TProduct.HttpClient
{
///
/// HTTP请求辅助类
///
public class HttpRequestHelper
{
///
/// 获取
///
public static string Get(string url, Dictionary headers = null, Version version = null)
{
return Request(url, "GET", headers, null, version);
}
///
/// 提交
///
public static string Post(string url, Dictionary headers = null, string data = null, Version version = null)
{
return Request(url, "POST", headers, data, version);
}
///
/// 更新
///
public static string Put(string url, Dictionary headers = null, string data = null, Version version = null)
{
return Request(url, "PUT", headers, data, version);
}
///
/// 删除
///
public static string Delete(string url, Dictionary headers = null, string data = null, Version version = null)
{
return Request(url, "DELETE", headers, data, version);
}
//请求
private static string Request(string url, string type, Dictionary headers = null, string data = null, Version version = null)
{
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = type;
request.ContentType = "application/json";
if (version != null)
{ //默认是HttpVersion.Version11
request.ProtocolVersion = version;
}
if (headers != null && headers.Count > 0)
{
foreach (var header in headers)
{
request.Headers.Add(header.Key, header.Value);
}
}
#region 注释
//request.Timeout = 10 * 1000;//请求超时时间
//if (!string.IsNullOrEmpty(data))
//{
//request.ContentLength = Encoding.UTF8.GetBytes(data).Length;
//}
#endregion
if (!string.IsNullOrEmpty(data))
{
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(data);
streamWriter.Flush();
}
}
string responseText;
using (var response = (HttpWebResponse)request.GetResponse())
using (var reader = new StreamReader(response.GetResponseStream()))
{
responseText = reader.ReadToEnd();
}
return responseText;
}
}
}