C# .Net WebClient http及https请求
C# .Net WebClient http及https请求及上传文件
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.Text.RegularExpressions; using System.Web; namespace Tools { public class RestfullRequest { public static string Request(string url, string method, string contentType, string data, NameValueCollection header = null, NetworkCredential credential = null, string proxyAddress = null, Encoding responseEncoding = null) { var request = (HttpWebRequest)WebRequest.Create(url); if (url.StartsWith("https://")) { ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(RemoteCertificateValidate);//验证服务器证书回调自动验证 ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; } request.Method = method; if (!string.IsNullOrEmpty(contentType)) request.ContentType = contentType; if (header != null) request.Headers.Add(header); if (credential != null) request.Credentials = credential; if (!string.IsNullOrEmpty(proxyAddress)) { IWebProxy proxy = new WebProxy(proxyAddress); proxy.Credentials = new NetworkCredential(); request.Proxy = proxy; } if (!string.IsNullOrEmpty(data)) { using (var swt = new StreamWriter(request.GetRequestStream())) { swt.Write(data); } } string result = string.Empty; using (WebResponse response = request.GetResponse()) { if (response.ContentType.IndexOf("octet-stream") > -1) { string dispositionStr = response.Headers["Content-Disposition"]; int fileNameI = dispositionStr.IndexOf("filename="); string fileName = dispositionStr.Substring(fileNameI + 9, dispositionStr.Length - (fileNameI + 9)); fileName = HttpUtility.UrlDecode(fileName, Encoding.UTF8); string downpath = AppDomain.CurrentDomain.BaseDirectory + "Download"; if (!Directory.Exists(downpath)) { Directory.CreateDirectory(downpath); } string downFile= downpath + "\\" + fileName; if (File.Exists(downFile)) { File.Delete(downFile); } Stream inStream = response.GetResponseStream(); using (Stream outStream = File.OpenWrite(downFile)) { byte[] buffer = new byte[8192]; int size = 0; while ((size = inStream.Read(buffer, 0, 8192)) > 0) { outStream.Write(buffer, 0, size); } } result = downFile; } else { Stream stream = response.GetResponseStream(); if (responseEncoding == null) responseEncoding = Encoding.UTF8; StreamReader myStreamReader = new StreamReader(stream, responseEncoding); result = myStreamReader.ReadToEnd(); myStreamReader.Close(); stream.Close(); //byte[] buf = new byte[1024]; //while (true) //{ // int len = stream.Read(buf, 0, buf.Length); // if (len <= 0)//len <= 0 跳出循环 // break; // if (responseEncoding == null) responseEncoding = Encoding.UTF8; // result += responseEncoding.GetString(buf, 0, len);//指定编码格式 //} } //using (var sr = new StreamReader(response.GetResponseStream())) //{ // result = sr.ReadToEnd(); //} } return result; } public static string WebClientRequest(string url, string method, string contentType = "application/json", NameValueCollection header = null, string postString = "") { try { //创建WebClient 对象 WebClient web = new WebClient(); //以form表单的形式上传 if (header != null) web.Headers.Add(header); web.Headers.Add("Content-Type", contentType); // 转化成二进制数组0 byte[] postData = Encoding.UTF8.GetBytes(postString); web.Headers.Add("ContentLength", postData.Length.ToString()); if (Regex.IsMatch(url, "^https://")) { ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(RemoteCertificateValidate);//验证服务器证书回调自动验证 ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; } // 上传数据 byte[] responseData = web.UploadData(url, method, postData); //获取返回的二进制数据. string ret = Encoding.UTF8.GetString(responseData); return ret; } catch (Exception e) { return "err_" + e.Message; } } /// <summary> /// HttpWebRequest发送文件 /// </summary> /// <param name="url">url</param> /// <param name="fileName">文件路径</param> /// <param name="fileParaName">文件参数名</param> /// <param name="contentType">contentType</param> /// <param name="nameValueCollection">其余要附带的参数键值对</param> public static string RequestUploadFile(string url, byte[] buffer, string fileParaName, string fileName, NameValueCollection nameValueCollection, string contentType="application/octet-stream") { string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x"); byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n"); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.ContentType = "multipart/form-data; boundary=" + boundary; request.Method = "POST"; request.KeepAlive = true; request.Credentials = CredentialCache.DefaultCredentials; Stream requestStream = request.GetRequestStream(); string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}"; if (nameValueCollection != null) { foreach (string key in nameValueCollection.Keys) { requestStream.Write(boundarybytes, 0, boundarybytes.Length); string formitem = string.Format(formdataTemplate, key, nameValueCollection[key]); byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem); requestStream.Write(formitembytes, 0, formitembytes.Length); } } requestStream.Write(boundarybytes, 0, boundarybytes.Length); string header = string.Format("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n", fileParaName, fileName, contentType); byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header); requestStream.Write(headerbytes, 0, headerbytes.Length); //FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read); //byte[] buffer = new byte[4096]; //int bytesRead = 0; //while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) //{ // requestStream.Write(buffer, 0, bytesRead); //} //fileStream.Close(); requestStream.Write(buffer, 0, buffer.Length); byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n"); requestStream.Write(trailer, 0, trailer.Length); requestStream.Close(); WebResponse webResponse = null; try { webResponse = request.GetResponse(); Stream responseStream = webResponse.GetResponseStream(); StreamReader streamReader = new StreamReader(responseStream); string result = streamReader.ReadToEnd(); return result; } catch (Exception ex) { if (webResponse != null) { webResponse.Close(); webResponse = null; } } finally { request = null; } return ""; } private static bool RemoteCertificateValidate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error) { //为了通过证书验证,总是返回true return true; } public static bool IsFileInUse(string fileName) { bool inUse = true; FileStream fs = null; try { fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.None); inUse = false; } catch { } finally { if (fs != null) fs.Close(); } return inUse;//true表示正在使用,false没有使用 } } }
常见问题:
1、远程服务器返回错误: (500) 内部服务器错误
原因可能:同样的参数报错导致。
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.Web; namespace Tools { public class RestfullRequest { public static string Request(string url, string method, string contentType, string data, NameValueCollection header = null, NetworkCredential credential = null, string proxyAddress = null, Encoding responseEncoding = null) { var request = (HttpWebRequest)WebRequest.Create(url); if (url.StartsWith("https://")) { ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(RemoteCertificateValidate);//验证服务器证书回调自动验证 ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; } request.Method = method; if (!string.IsNullOrEmpty(contentType)) request.ContentType = contentType; if (header != null) request.Headers.Add(header); if (credential != null) request.Credentials = credential; if (!string.IsNullOrEmpty(proxyAddress)) { IWebProxy proxy = new WebProxy(proxyAddress); proxy.Credentials = new NetworkCredential(); request.Proxy = proxy; } if (!string.IsNullOrEmpty(data)) { using (var swt = new StreamWriter(request.GetRequestStream())) { swt.Write(data); } } string result = string.Empty; using (WebResponse response = request.GetResponse()) { if (response.ContentType.IndexOf("octet-stream") > -1) { string dispositionStr = response.Headers["Content-Disposition"]; int fileNameI = dispositionStr.IndexOf("filename="); string fileName = dispositionStr.Substring(fileNameI + 9, dispositionStr.Length - (fileNameI + 9)); fileName = HttpUtility.UrlDecode(fileName, Encoding.UTF8); string downpath = AppDomain.CurrentDomain.BaseDirectory + "Download"; if (!Directory.Exists(downpath)) { Directory.CreateDirectory(downpath); } string downFile= downpath + "\\" + fileName; if (File.Exists(downFile)) { File.Delete(downFile); } Stream inStream = response.GetResponseStream(); using (Stream outStream = File.OpenWrite(downFile)) { byte[] buffer = new byte[8192]; int size = 0; while ((size = inStream.Read(buffer, 0, 8192)) > 0) { outStream.Write(buffer, 0, size); } } result = downFile; } else { Stream stream = response.GetResponseStream(); if (responseEncoding == null) responseEncoding = Encoding.UTF8; StreamReader myStreamReader = new StreamReader(stream, responseEncoding); result = myStreamReader.ReadToEnd(); myStreamReader.Close(); stream.Close(); //byte[] buf = new byte[1024]; //while (true) //{ // int len = stream.Read(buf, 0, buf.Length); // if (len <= 0)//len <= 0 跳出循环 // break; // if (responseEncoding == null) responseEncoding = Encoding.UTF8; // result += responseEncoding.GetString(buf, 0, len);//指定编码格式 //} } //using (var sr = new StreamReader(response.GetResponseStream())) //{ // result = sr.ReadToEnd(); //} } return result; } /// <summary> /// HttpWebRequest发送文件 /// </summary> /// <param name="url">url</param> /// <param name="fileName">文件路径</param> /// <param name="fileParaName">文件参数名</param> /// <param name="contentType">contentType</param> /// <param name="nameValueCollection">其余要附带的参数键值对</param> public static string RequestUploadFile(string url, byte[] buffer, string fileParaName, string fileName, NameValueCollection nameValueCollection, string contentType="application/octet-stream") { string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x"); byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n"); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.ContentType = "multipart/form-data; boundary=" + boundary; request.Method = "POST"; request.KeepAlive = true; request.Credentials = CredentialCache.DefaultCredentials; Stream requestStream = request.GetRequestStream(); string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}"; if (nameValueCollection != null) { foreach (string key in nameValueCollection.Keys) { requestStream.Write(boundarybytes, 0, boundarybytes.Length); string formitem = string.Format(formdataTemplate, key, nameValueCollection[key]); byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem); requestStream.Write(formitembytes, 0, formitembytes.Length); } } requestStream.Write(boundarybytes, 0, boundarybytes.Length); string header = string.Format("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n", fileParaName, fileName, contentType); byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header); requestStream.Write(headerbytes, 0, headerbytes.Length); //FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read); //byte[] buffer = new byte[4096]; //int bytesRead = 0; //while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) //{ // requestStream.Write(buffer, 0, bytesRead); //} //fileStream.Close(); requestStream.Write(buffer, 0, buffer.Length); byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n"); requestStream.Write(trailer, 0, trailer.Length); requestStream.Close(); WebResponse webResponse = null; try { webResponse = request.GetResponse(); Stream responseStream = webResponse.GetResponseStream(); StreamReader streamReader = new StreamReader(responseStream); string result = streamReader.ReadToEnd(); return result; } catch (Exception ex) { if (webResponse != null) { webResponse.Close(); webResponse = null; } } finally { request = null; } return ""; } private static bool RemoteCertificateValidate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error) { //为了通过证书验证,总是返回true return true; } public static bool IsFileInUse(string fileName) { bool inUse = true; FileStream fs = null; try { fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.None); inUse = false; } catch { } finally { if (fs != null) fs.Close(); } return inUse;//true表示正在使用,false没有使用 } } }