1. 程式人生 > 其它 >C# .Net WebClient http及https請求

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.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; } 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沒有使用 } } }