123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403 |
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.IO;
- using System.Net;
- using System.Net.Http;
- using System.Net.Security;
- using System.Security.Cryptography.X509Certificates;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- namespace CZFW.Core
- {
- public static class HttpHelper
- {
- #region POST
- /// <summary>
- /// HTTP POST方式请求数据
- /// </summary>
- /// <param name="url">URL.</param>
- /// <param name="param">POST的数据</param>
- /// <returns></returns>
- public static string HttpPost(string url, string param = null)
- {
- HttpWebRequest request;
- //如果是发送HTTPS请求
- if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
- {
- ServicePointManager.ServerCertificateValidationCallback = CheckValidationResult;
- request = WebRequest.Create(url) as HttpWebRequest;
- request.ProtocolVersion = HttpVersion.Version10;
- }
- else
- {
- request = WebRequest.Create(url) as HttpWebRequest;
- }
- request.Method = "POST";
- request.ContentType = "application/x-www-form-urlencoded";
- request.Accept = "*/*";
- request.Timeout = 15000;
- request.AllowAutoRedirect = false;
- string responseStr;
- var requestStream = new StreamWriter(request.GetRequestStream());
- requestStream.Write(param);
- requestStream.Close();
- var response = request.GetResponse();
- {
- StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
- responseStr = reader.ReadToEnd();
- reader.Close();
- }
- return responseStr;
- }
- private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
- {
- return true; //总是接受
- }
- public static string BuildRequest(string strUrl, Dictionary<string, string> dicPara, string fileName)
- {
- string contentType = "image/jpeg";
- //待请求参数数组
- FileStream pic = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
- byte[] picByte = new byte[pic.Length];
- pic.Read(picByte, 0, picByte.Length);
- int lengthFile = picByte.Length;
- //构造请求地址
- //设置HttpWebRequest基本信息
- HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strUrl);
- //设置请求方式:get、post
- request.Method = "POST";
- //设置boundaryValue
- string boundaryValue = DateTime.Now.Ticks.ToString("x");
- string boundary = "--" + boundaryValue;
- request.ContentType = "\r\nmultipart/form-data; boundary=" + boundaryValue;
- //设置KeepAlive
- request.KeepAlive = true;
- //设置请求数据,拼接成字符串
- StringBuilder sbHtml = new StringBuilder();
- foreach (KeyValuePair<string, string> key in dicPara)
- {
- sbHtml.Append(boundary + "\r\nContent-Disposition: form-data; name=\"" + key.Key + "\"\r\n\r\n" + key.Value + "\r\n");
- }
- sbHtml.Append(boundary + "\r\nContent-Disposition: form-data; name=\"pic\"; filename=\"");
- sbHtml.Append(fileName);
- sbHtml.Append("\"\r\nContent-Type: " + contentType + "\r\n\r\n");
- string postHeader = sbHtml.ToString();
- //将请求数据字符串类型根据编码格式转换成字节流
- Encoding code = Encoding.GetEncoding("UTF-8");
- byte[] postHeaderBytes = code.GetBytes(postHeader);
- byte[] boundayBytes = Encoding.ASCII.GetBytes("\r\n" + boundary + "--\r\n");
- //设置长度
- long length = postHeaderBytes.Length + lengthFile + boundayBytes.Length;
- request.ContentLength = length;
- //请求远程HTTP
- Stream requestStream = request.GetRequestStream();
- //发送数据请求服务器
- requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
- requestStream.Write(picByte, 0, lengthFile);
- requestStream.Write(boundayBytes, 0, boundayBytes.Length);
- HttpWebResponse httpWResp = (HttpWebResponse)request.GetResponse();
- var myStream = httpWResp.GetResponseStream();
- //读取处理结果
- StreamReader reader = new StreamReader(myStream, code);
- StringBuilder responseData = new StringBuilder();
- string line;
- while ((line = reader.ReadLine()) != null)
- {
- responseData.Append(line);
- }
- myStream.Close();
- pic.Close();
- return responseData.ToString();
- }
- #endregion
- #region Put
- /// <summary>
- /// HTTP Put方式请求数据.
- /// </summary>
- /// <param name="url">URL.</param>
- /// <param name="param"></param>
- /// <returns></returns>
- public static string HttpPut(string url, string param = null)
- {
- HttpWebRequest request;
- //如果是发送HTTPS请求
- if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
- {
- ServicePointManager.ServerCertificateValidationCallback = CheckValidationResult;
- request = WebRequest.Create(url) as HttpWebRequest;
- request.ProtocolVersion = HttpVersion.Version10;
- }
- else
- {
- request = WebRequest.Create(url) as HttpWebRequest;
- }
- request.Method = "PUT";
- request.ContentType = "application/x-www-form-urlencoded";
- request.Accept = "*/*";
- request.Timeout = 15000;
- request.AllowAutoRedirect = false;
- var requestStream = new StreamWriter(request.GetRequestStream());
- requestStream.Write(param);
- requestStream.Close();
- var response = request.GetResponse();
- StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
- var responseStr = reader.ReadToEnd();
- reader.Close();
- return responseStr;
- }
- #endregion
- #region Delete
- /// <summary>
- /// HTTP Delete方式请求数据.
- /// </summary>
- /// <param name="url">URL.</param>
- /// <param name="param"></param>
- /// <returns></returns>
- public static string HttpDelete(string url, string param = null)
- {
- HttpWebRequest request;
- //如果是发送HTTPS请求
- if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
- {
- ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
- request = WebRequest.Create(url) as HttpWebRequest;
- request.ProtocolVersion = HttpVersion.Version10;
- }
- else
- {
- request = WebRequest.Create(url) as HttpWebRequest;
- }
- request.Method = "Delete";
- request.ContentType = "application/x-www-form-urlencoded";
- request.Accept = "*/*";
- request.Timeout = 15000;
- request.AllowAutoRedirect = false;
- string responseStr;
- var requestStream = new StreamWriter(request.GetRequestStream());
- requestStream.Write(param);
- requestStream.Close();
- var response = request.GetResponse();
- {
- StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
- responseStr = reader.ReadToEnd();
- reader.Close();
- }
- return responseStr;
- }
- #endregion
- #region Get
- /// <summary>
- /// HTTP GET方式请求数据.
- /// </summary>
- /// <param name="url">URL.</param>
- /// <param name="headht"></param>
- /// <returns></returns>
- public static string HttpGet(string url, Hashtable headht = null)
- {
- HttpWebRequest request;
- //如果是发送HTTPS请求
- if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
- {
- ServicePointManager.ServerCertificateValidationCallback = CheckValidationResult;
- request = WebRequest.Create(url) as HttpWebRequest;
- request.ProtocolVersion = HttpVersion.Version10;
- }
- else
- {
- request = WebRequest.Create(url) as HttpWebRequest;
- }
- request.Method = "GET";
- //request.ContentType = "application/x-www-form-urlencoded";
- request.Accept = "*/*";
- request.Timeout = 15000;
- request.AllowAutoRedirect = false;
-
- string responseStr;
- if (headht != null)
- {
- foreach (DictionaryEntry item in headht)
- {
- request.Headers.Add(item.Key.ToString(), item.Value.ToString());
- }
- }
- var response = request.GetResponse();
- {
- var test = response.GetResponseStream();
-
- StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
- responseStr = reader.ReadToEnd();
- reader.Close();
- }
- return responseStr;
- }
- public static string HttpGet(string url, Encoding encodeing, Hashtable headht = null)
- {
- HttpWebRequest request;
- //如果是发送HTTPS请求
- if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
- {
- ServicePointManager.ServerCertificateValidationCallback = CheckValidationResult;
- request = WebRequest.Create(url) as HttpWebRequest;
- request.ProtocolVersion = HttpVersion.Version10;
- }
- else
- {
- request = WebRequest.Create(url) as HttpWebRequest;
- }
- request.Method = "GET";
- //request.ContentType = "application/x-www-form-urlencoded";
- request.Accept = "*/*";
- request.Timeout = 15000;
- request.AllowAutoRedirect = false;
- string responseStr;
- if (headht != null)
- {
- foreach (DictionaryEntry item in headht)
- {
- request.Headers.Add(item.Key.ToString(), item.Value.ToString());
- }
- }
- var response = request.GetResponse();
- {
- StreamReader reader = new StreamReader(response.GetResponseStream(), encodeing);
- responseStr = reader.ReadToEnd();
- reader.Close();
- }
- return responseStr;
- }
- #endregion
- #region Post With Pic
- /// <summary>
- /// HTTP POST方式请求数据(带图片)
- /// </summary>
- /// <param name="url">URL</param>
- /// <param name="param">POST的数据</param>
- /// <param name="fileByte">图片</param>
- /// <returns></returns>
- public static string HttpPost(string url, IDictionary<object, object> param, byte[] fileByte)
- {
- string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
- byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
- HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
- wr.ContentType = "multipart/form-data; boundary=" + boundary;
- wr.Method = "POST";
- wr.KeepAlive = true;
- wr.Credentials = CredentialCache.DefaultCredentials;
- Stream rs = wr.GetRequestStream();
- const string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
- foreach (string key in param.Keys)
- {
- rs.Write(boundarybytes, 0, boundarybytes.Length);
- string formitem = string.Format(formdataTemplate, key, param[key]);
- byte[] formitembytes = Encoding.UTF8.GetBytes(formitem);
- rs.Write(formitembytes, 0, formitembytes.Length);
- }
- rs.Write(boundarybytes, 0, boundarybytes.Length);
- const string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
- string header = string.Format(headerTemplate, "pic", fileByte, "text/plain");//image/jpeg
- byte[] headerbytes = Encoding.UTF8.GetBytes(header);
- rs.Write(headerbytes, 0, headerbytes.Length);
- rs.Write(fileByte, 0, fileByte.Length);
- byte[] trailer = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
- rs.Write(trailer, 0, trailer.Length);
- rs.Close();
- var wresp = wr.GetResponse();
- Stream stream2 = wresp.GetResponseStream();
- StreamReader reader2 = new StreamReader(stream2);
- var responseStr = reader2.ReadToEnd();
- return responseStr;
- }
- #endregion
- #region HttpsClient
- /// <summary>
- /// 创建HttpClient
- /// </summary>
- /// <returns></returns>
- public static HttpClient CreateHttpClient(string url)
- {
- HttpClient httpclient;
- //如果是发送HTTPS请求
- if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
- {
- ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
- httpclient = new HttpClient();
- }
- else
- {
- httpclient = new HttpClient();
- }
- return httpclient;
- }
- #endregion
- public static async Task<string> HttpPost2(string url, string param = null)
- {
- HttpWebRequest request;
- request = WebRequest.Create(url) as HttpWebRequest;
- request.Method = "POST";
- request.ContentType = "application/json";
- request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36";
- request.Timeout = 15000;
- request.AllowAutoRedirect = false;
- string responseStr;
- var requestStream = new StreamWriter(request.GetRequestStream());
- requestStream.Write(param);
- requestStream.Close();
- var response = await request.GetResponseAsync();
- StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
- responseStr = reader.ReadToEnd();
- reader.Close();
- return responseStr;
- ;
- }
- public async static Task<string> HttpPostAsync(string url, string param = null)
- {
- HttpWebRequest request;
- request = WebRequest.Create(url) as HttpWebRequest;
- request.Method = "POST";
- request.ContentType = "application/x-www-form-urlencoded";
- request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36";
- request.Timeout = 15000;
- request.AllowAutoRedirect = false;
- string responseStr;
- var requestStream = new StreamWriter(request.GetRequestStream());
- requestStream.Write(param);
- requestStream.Close();
- var response = await request.GetResponseAsync();
- StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
- responseStr = await reader.ReadToEndAsync();
- reader.Close();
- return responseStr;
- }
-
- }
- }
|