[C#] 呼叫curl開啟https網頁
阿新 • • 發佈:2019-01-28
有些特定的https網站,用C#自帶的HttpClient可能會無法訪問,而用瀏覽器訪問卻都正常。比如: https://www.nasdaq.com/
這是由於C#的http client沒有完整實現最新的SSL規範。
此時我們有三個選擇:
1、使用第三方的http實現:很遺憾,沒找到。在C#下幾乎沒有第三方的http client,大概是官方的http client實現的太好了。
2、使用libcurl:維護不佳,libcurlnet或者curlsharp都不好用。
3、通過Process類直接呼叫curl.exe並獲得輸出。
我這裡貼一下方案3的實現:
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace PowerCurl { public class PowerCurl { public static string Get(string url) { var rr = Guid.NewGuid().ToString(); string tmpFile = Path.GetTempPath() + "/curl_temp_" + rr + ".txt"; Process p = new Process(); p.StartInfo = new ProcessStartInfo(); p.StartInfo.FileName = "curl.exe"; p.StartInfo.Arguments = string.Format("-o {0} {1}", tmpFile, url); p.StartInfo.CreateNoWindow = true; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.Start(); int count = 0; while (count < 1000) { Thread.Sleep(10); if (File.Exists(tmpFile)) { while (true) { try { var ts = File.ReadAllText(tmpFile); break; } catch (Exception) { //tmpFile還沒放開,說明還沒收完 Thread.Sleep(10); } } break; } count++; } var ss = File.ReadAllText(tmpFile); File.Delete(tmpFile); return ss; } } }