using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Security; using System.Security.Cryptography.X509Certificates; using System.Text; namespace NaTeWebApi.Services { public class HttpHelper { public static string WebPost(string url, string postData, string cotentType = "application/json",string token = "",string timestamp = "") { Console.WriteLine(url); WebRequest request = WebRequest.Create(url); request.Method = "POST"; //string postData = JsonConvert.SerializeObject(data); byte[] byteArray = Encoding.UTF8.GetBytes(postData); request.ContentType = cotentType; request.ContentLength = byteArray.Length; request.Timeout = 6000; try { Stream dataStream = request.GetRequestStream(); dataStream.Write(byteArray, 0, byteArray.Length); dataStream.Close(); WebResponse response = request.GetResponse(); //Console.WriteLine(((HttpWebResponse)response).StatusDescription); dataStream = response.GetResponseStream(); StreamReader reader = new StreamReader(dataStream, Encoding.UTF8); string responseFromServer = reader.ReadToEnd(); reader.Close(); dataStream.Close(); response.Close(); return responseFromServer; } catch (Exception e) { Console.WriteLine(e.Message); return ""; } } /// /// 内网证书验证通讯请求 /// /// /// /// /// public string PostData(string apiUrl, string queryString, string token) { //请求路径 string url = apiUrl; //定义request并设置request的路径 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "post"; request.ServerCertificateValidationCallback += (sender, cert, chain, error) => { return true; }; //初始化request参数 string postData = queryString; //设置参数的编码格式,解决中文乱码 byte[] byteArray = Encoding.UTF8.GetBytes(postData); //设置request的MIME类型及内容长度 request.ContentType = "application/json"; request.ContentLength = byteArray.Length; request.Headers.Add("Authorization", token); //打开request字符流 Stream dataStream = request.GetRequestStream(); dataStream.Write(byteArray, 0, byteArray.Length); dataStream.Close(); //定义response为前面的request响应 WebResponse response = request.GetResponse(); //获取相应的状态代码 Console.WriteLine(((HttpWebResponse)response).StatusDescription); //定义response字符流 dataStream = response.GetResponseStream(); StreamReader reader = new StreamReader(dataStream); string responseFromServer = reader.ReadToEnd();//读取所有 Console.WriteLine(responseFromServer); return responseFromServer; } /// /// 带证书请求 /// /// 请求地址 /// 请求方式 /// 请求的字符串 /// 请求头 /// 证书路径 /// 证书密码 /// 响应结果 /// /// Console.WriteLine(HttpWebRequestWithCertificate("https://host:port/path","POST", "{JsonData}", null,@"......\xxx.p12","123456")); /// public string HttpsWebPost(string url, string method, string content, Dictionary headers, string certificatePath, string certPassword) { string result = string.Empty; try { ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | (SecurityProtocolType)768 | (SecurityProtocolType)3072 | (SecurityProtocolType)0x300 | (SecurityProtocolType)0xC00; ServicePointManager.ServerCertificateValidationCallback += (q, w, e, r) => r == SslPolicyErrors.None; X509Certificate2 cer = new X509Certificate2(certificatePath, certPassword, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable); byte[] bytes = System.Text.Encoding.UTF8.GetBytes(content); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.ClientCertificates.Add(cer);//必须先最先配置ClientCertificates字段,否则会报有关SSL/TLS错 request.ContentType = "application/json"; request.Method = method; request.ContentLength = bytes.Length; if (headers != null && headers.Count > 0) { foreach (var item in headers) { request.Headers.Add(item.Key, item.Value); } } using (Stream requestStream = request.GetRequestStream()) { requestStream.Write(bytes, 0, bytes.Length); requestStream.Close(); } HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream responseStream = response.GetResponseStream(); if (responseStream != null) { StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.UTF8); result = reader.ReadToEnd().Trim(); reader.Close(); responseStream.Close(); request.Abort(); response.Close(); } } catch (Exception ex) { return ex.Message + ex.StackTrace; } return result; } public string HttpsWebPost(string url, string postData, string cotentType = "application/json") { Console.WriteLine(url); //C:\\Users\\Administrator\\Desktop\\httpsPfx.pfx C:\\mycert.cer //X509Certificate cert = X509Certificate.CreateFromCertFile("C:\\Users\\Administrator\\Desktop\\httpsPfx.pfx"); ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | (SecurityProtocolType)768 | (SecurityProtocolType)3072 | (SecurityProtocolType)0x300 | (SecurityProtocolType)0xC00; X509Certificate2 cert = new X509Certificate2("C:\\Users\\Administrator\\Desktop\\httpsPfx.pfx", "123456", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.DefaultKeySet); // Handle any certificate errors on the certificate from the server. //ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; //string postData = JsonConvert.SerializeObject(data); byte[] byteArray = Encoding.UTF8.GetBytes(postData); request.ContentType = cotentType; request.ContentLength = byteArray.Length; request.Timeout = 5000; request.ClientCertificates.Add(cert); try { Stream dataStream = request.GetRequestStream(); dataStream.Write(byteArray, 0, byteArray.Length); dataStream.Close(); WebResponse response = request.GetResponse(); //Console.WriteLine(((HttpWebResponse)response).StatusDescription); dataStream = response.GetResponseStream(); StreamReader reader = new StreamReader(dataStream, Encoding.UTF8); string responseFromServer = reader.ReadToEnd(); reader.Close(); dataStream.Close(); response.Close(); return responseFromServer; } catch (Exception e) { Console.WriteLine(e.Message); return ""; } } public string WebGet(string url) { //using (var client = new HttpClient()) { // //请求结果 // string result = client.GetAsync(url).Result.Content.ReadAsStringAsync().Result; // Console.WriteLine(result); // return result; //} //Console.WriteLine(url); WebRequest request = WebRequest.Create(url); request.Timeout = 6000; request.Method = "GET"; try { WebResponse response = request.GetResponse(); Stream dataStream = response.GetResponseStream(); StreamReader reader = new StreamReader(dataStream); string responseFromServer = reader.ReadToEnd(); reader.Close(); dataStream.Close(); response.Close(); Console.WriteLine(responseFromServer); return responseFromServer; } catch (Exception ex) { Console.WriteLine(ex.Message); return ""; } } public string Get(string url, string contentType = "application/x-www-form-urlencoded") { WebRequest request = WebRequest.Create(url); request.Method = "Get"; request.ContentType = contentType; StreamReader reader = null; Stream stream = null; WebResponse rsp = null; try { rsp = request.GetResponse(); stream = rsp.GetResponseStream(); reader = new StreamReader(stream); return reader.ReadToEnd(); } catch { return ""; } finally { // 释放资源 if (reader != null) reader.Close(); if (stream != null) stream.Close(); if (rsp != null) rsp.Close(); } } public string Post(string url, string postData, string contentType = "application/json", string sessionId = "") { WebRequest request = WebRequest.Create(url); request.Method = "POST"; byte[] byteArray = Encoding.UTF8.GetBytes(postData); request.ContentType = contentType; request.ContentLength = byteArray.Length; if (sessionId != "") { request.Headers.Set("ASP.NET_SessionId", sessionId); } StreamReader reader = null; Stream stream = null; WebResponse rsp = null; try { stream = request.GetRequestStream(); stream.Write(byteArray, 0, byteArray.Length); stream.Close(); rsp = request.GetResponse(); stream = rsp.GetResponseStream(); reader = new StreamReader(stream); return reader.ReadToEnd(); } catch { return ""; } finally { // 释放资源 if (reader != null) reader.Close(); if (stream != null) stream.Close(); if (rsp != null) rsp.Close(); } } public string Post(string url, Dictionary dic) { var param = dic.Select(a => { return string.Format("{0}={1}", a.Key, a.Value); }).ToList(); return Post(url, string.Join("&", param), "application/x-www-form-urlencoded"); } public string PostWithCookie(string url, string sessinId) { return PostWithCookie(url, "", "", sessinId); } public string PostWithCookie(string url, string postData, string contentType = "application/json", string sessionId = "") { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; byte[] byteArray = Encoding.UTF8.GetBytes(postData); request.ContentType = contentType; request.ContentLength = byteArray.Length; if (sessionId != "") { request.CookieContainer = new CookieContainer(); request.CookieContainer.SetCookies(new Uri("http://" + request.RequestUri.Authority), "ASP.NET_SessionId=" + sessionId); } StreamReader reader = null; Stream stream = null; WebResponse rsp = null; try { stream = request.GetRequestStream(); stream.Write(byteArray, 0, byteArray.Length); stream.Close(); rsp = request.GetResponse(); stream = rsp.GetResponseStream(); reader = new StreamReader(stream); return reader.ReadToEnd(); } catch { return ""; } finally { // 释放资源 if (reader != null) reader.Close(); if (stream != null) stream.Close(); if (rsp != null) rsp.Close(); } } } }