using System;
|
using System.IO;
|
using System.Net;
|
|
namespace IStation.WinFrmUI.CalcErQu
|
{
|
/// <summary>
|
/// HTTP请求辅助类
|
/// </summary>
|
public class HttpRequestHelper
|
{
|
/// <summary>
|
/// 获取
|
/// </summary>
|
public static string Get(string url, Version version = null)
|
{
|
return Request(url, "GET", null, version);
|
}
|
|
/// <summary>
|
/// 提交
|
/// </summary>
|
public static string Post(string url, string data = null, Version version = null)
|
{
|
return Request(url, "POST", data, version);
|
}
|
|
|
//请求
|
private static string Request(string url, string type, string data = null, Version version = null)
|
{
|
var request = (HttpWebRequest)WebRequest.Create(url);
|
request.Method = type;
|
request.ContentType = "application/json";
|
request.KeepAlive = false;
|
if (version != null)
|
{
|
//默认是HttpVersion.Version11
|
request.ProtocolVersion = version;
|
}
|
|
#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;
|
}
|
|
|
|
}
|
}
|