using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
namespace Huinaozn.ASleepPC.Tools.Utils
{
public static class HttpWebResponseUtility
{
/// <summary>
/// 通用请求方法
/// </summary>
/// <param name="url"></param>
/// <param name="datas"></param>
/// <param name="method">POST GET PUT DELETE</param>
/// <param name="contentType">"POST application/x-www-form-urlencoded; charset=UTF-8"</param>
/// <param name="encoding"></param>
/// <returns></returns>
public static string HttpRequest(string url, string data, string method = "POST", string contentType = "application/json", Encoding encoding = null, string token = null)
{
if (encoding == null)
encoding = Encoding.UTF8;
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Method = method;
request.Timeout = 150000;
request.AllowAutoRedirect = false;
//添加头部Authorization验证token
if (token != null)
{
request.Headers.Add("Authorization", token);
}
if (!string.IsNullOrEmpty(contentType))
{
request.ContentType = contentType;
}
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
}
Stream requestStream = null;
string responseStr = null;
try
{
if (data != null)
{
byte[] datas = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(data);//data可以直接传字节类型 byte[] data,然后这一段就可以去掉
request.ContentLength = datas.Length;
requestStream = request.GetRequestStream();
requestStream.Write(datas, 0, datas.Length);
requestStream.Close();
}
else
{
request.ContentLength = 0;
}
using (HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse())
{
Stream getStream = webResponse.GetResponseStream();
byte[] outBytes = ReadFully(getStream);
getStream.Close();
responseStr = Encoding.UTF8.GetString(outBytes);
}
}
catch (Exception)
{
throw;
}
finally
{
request = null;
requestStream = null;
}
return responseStr;
}
public static string HttpRequest(string url, string data, string userName, string password, string method = "POST", string contentType = "application/json", Encoding encoding = null, string token = null)
{
if (encoding == null)
encoding = Encoding.UTF8;
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Method = method;
request.Timeout = 150000;
request.AllowAutoRedirect = false;
CredentialCache credentialCache = new CredentialCache();
credentialCache.Add(new Uri(url), "Basic", new NetworkCredential(userName, password));
request.Credentials = credentialCache;
//添加头部Authorization验证token
if (token != null)
{
request.Headers.Add("Authorization", token);
}
if (!string.IsNullOrEmpty(contentType))
{
request.ContentType = contentType;
}
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
}
Stream requestStream = null;
string responseStr = null;
try
{
if (data != null)
{
byte[] datas = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(data);//data可以直接传字节类型 byte[] data,然后这一段就可以去掉
request.ContentLength = datas.Length;
requestStream = request.GetRequestStream();
requestStream.Write(datas, 0, datas.Length);
requestStream.Close();
}
else
{
request.ContentLength = 0;
}
using (HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse())
{
Stream getStream = webResponse.GetResponseStream();
byte[] outBytes = ReadFully(getStream);
getStream.Close();
responseStr = Encoding.UTF8.GetString(outBytes);
}
}
catch (Exception)
{
throw;
}
finally
{
request = null;
requestStream = null;
}
return responseStr;
}
/// <summary>
/// HTTP请求(包含多分部数据,multipart/form-data)。
/// 将多个文件以及多个参数以多分部数据表单方式上传到指定url的服务器
/// </summary>
/// <param name="url">请求目标URL</param>
/// <param name="fileFullNames">待上传的文件列表(包含全路径的完全限定名)。如果某个文件不存在,则忽略不上传</param>
/// <param name="kVDatas">请求时表单键值对数据。</param>
/// <param name="method">请求的方法。请使用 WebRequestMethods.Http 的枚举值</param>
/// <param name="timeOut">获取或设置 <see cref="M:System.Net.HttpWebRequest.GetResponse" /> 和
/// <see cref="M:System.Net.HttpWebRequest.GetRequestStream" /> 方法的超时值(以毫秒为单位)。
/// -1 表示永不超时
/// </param>
/// <returns></returns>
public static string HttpPost(string url, string fileFullNames, NameValueCollection kVDatas = null, string method = WebRequestMethods.Http.Post, int timeOut = -1)
{
try
{
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
byte[] endbytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
//1.HttpWebRequest
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.Method = "POST";
request.KeepAlive = true;
request.Timeout = timeOut;
CredentialCache credentialCache = new CredentialCache();
credentialCache.Add(new Uri(url), "Basic", new NetworkCredential("member", "secret"));
request.Credentials = credentialCache;
request.ServicePoint.Expect100Continue = false;
using (Stream stream = request.GetRequestStream())
{
//1.1 key/value
string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
if (kVDatas != null)
{
foreach (string key in kVDatas.Keys)
{
stream.Write(boundarybytes, 0, boundarybytes.Length);
string formitem = string.Format(formdataTemplate, key, kVDatas[key]);
byte[] formitembytes = Encoding.GetEncoding("UTF-8").GetBytes(formitem);
stream.Write(formitembytes, 0, formitembytes.Length);
}
}
stream.Write(endbytes, 0, endbytes.Length);
}
//2.WebResponse
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader stream = new StreamReader(response.GetResponseStream()))
{
return stream.ReadToEnd();
}
}
catch (Exception e)
{
throw e;
}
}
private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true; //总是接受
}
public static byte[] ReadFully(Stream stream)
{
byte[] buffer = new byte[512];
using (MemoryStream ms = new MemoryStream())
{
while (true)
{
int read = stream.Read(buffer, 0, buffer.Length);
if (read <= 0)
return ms.ToArray();
ms.Write(buffer, 0, read);
}
}
}
}
}