http的交互其实就是传递url参数,header参数,body参数等等,可以共用一个方法来发请求
public static class HttpHelper
{
/// <summary>
/// httpHelper
/// </summary>
/// <param name="url">URL.</param>
/// <param name="method"></param>
/// <param name="headht"></param>
/// <param name="param">POST的数据</param>
/// <returns></returns>
public static string HttpRequest(string url, HttpMethod method, Hashtable headht, string param = null)
{
HttpWebRequest request;
//如果是发送HTTPS请求
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
request = WebRequest.Create(url) as HttpWebRequest;
request.ProtocolVersion = HttpVersion.Version10;
}
else
{
request = WebRequest.Create(url) as HttpWebRequest;
}
if (headht != null)
{
foreach (DictionaryEntry item in headht)
{
request.Headers.Add(item.Key.ToString(), item.Value.ToString());
}
}
request.Method = method.ToString();
request.Accept = "*/*";
request.ContentType = "application/json; charset=utf-8";
request.Timeout = 15000;
request.AllowAutoRedirect = false;
StreamWriter requestStream = null;
WebResponse response = null;
string responseStr = null;
try
{
if (!string.IsNullOrWhiteSpace(param))
{
requestStream = new StreamWriter(request.GetRequestStream());
requestStream.Write(param);
requestStream.Close();
}
response = request.GetResponse();
if (response != null)
{
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
responseStr = reader.ReadToEnd();
reader.Close();
}
}
catch (WebException wex)
{
if (wex.Response != null)
{
using (var errorResponse = (HttpWebResponse)wex.Response)
{
using (var reader = new StreamReader(errorResponse.GetResponseStream()))
{
responseStr = reader.ReadToEnd();
}
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
finally
{
request = null;
requestStream = null;
response = null;
}
return responseStr;
}
//安全证书
private static bool CheckValidationResult(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors errors)
{
return true; //总是接受
}
public enum HttpMethod
{
POST = 0,
GET = 1,
PUT = 2,
DELETE = 3,
PATCH = 4
}
}