using System;
|
using System.Collections.Generic;
|
using System.IO;
|
using System.Net;
|
|
namespace TProduct.HttpClient
|
{
|
/// <summary>
|
/// HTTP请求辅助类
|
/// </summary>
|
public class HttpRequestHelper
|
{
|
/// <summary>
|
/// 获取
|
/// </summary>
|
public static string Get(string url, Dictionary<string, string> headers = null, Version version = null)
|
{
|
return Request(url, "GET", headers, null, version);
|
}
|
|
/// <summary>
|
/// 提交
|
/// </summary>
|
public static string Post(string url, Dictionary<string, string> headers = null, string data = null, Version version = null)
|
{
|
return Request(url, "POST", headers, data, version);
|
}
|
|
/// <summary>
|
/// 更新
|
/// </summary>
|
public static string Put(string url, Dictionary<string, string> headers = null, string data = null, Version version = null)
|
{
|
return Request(url, "PUT", headers, data, version);
|
}
|
|
/// <summary>
|
/// 删除
|
/// </summary>
|
public static string Delete(string url, Dictionary<string, string> headers = null, string data = null, Version version = null)
|
{
|
return Request(url, "DELETE", headers, data, version);
|
}
|
|
//请求
|
private static string Request(string url, string type, Dictionary<string, string> 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;
|
}
|
}
|
}
|