WIn7 下使用 NetHttpClient 請求HTPPS 網站


在WIN7 下使用 HttpClient 會報以下兩種錯 ;
1 Server Certificate Invalid or not present
2 Error sending data: (12175) 發生了安全錯誤.

3 System.Net.WebException: 請求被中止: 未能創建 SSL/TLS 安全通道。

經查詢資料是因為WIn7 默認不支持這個協議
詳細見:
https://support.microsoft.com/en-us/help/3140245/update-to-enable-tls-1-1-and-tls-1-2-as-default-secure-protocols-in-wi

解決方法:

指定 HttpClient.SecureProtocols  為TLS12

代碼:

procedure TForm2.Button1Click(Sender: TObject);
var
  str:string;
  ss:TStringStream;//TStreamstring
 begin
   try
    ss:=TStringStream.Create();
    //WIN 7 下使用 需要 指定 默認的協議TLS12
   http.SecureProtocols:=[THTTPSecureProtocol.TLS12];
    http.Get(url,ss);
    memo1.Text:=ss.DataString;
   finally
      ss.Free;
   end;
end;
View Code
   private void button1_Click(object sender, EventArgs e)
        {
            //ServicePointManager.ServerCertificateValidationCallback =
            //    new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
            string data;
            HttpClient http = new HttpClient();
            System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            HttpResponseMessage response = http.GetAsync("https://kindao1.github.io/LimitTW/").Result;
            textBox1.AppendText(response.ToString()+"\r\n");
            var re = response.Content.ReadAsStringAsync();
            data =re.Result;
            textBox1.AppendText(data);
        }
C# 代碼

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM