Last updated on 9 months ago
前言
这段时间在做外部接口,踩了点坑,记录一下
除了前期对外部接口和现有程序逻辑结合过程中的思路梳理。其中,有个坑,在net4.6
上写的demo,接口跑的溜不行,结果把程序放在产品中,嘎,废了。原因是,net 4
框架下不支持TLS1.2
协议,也就是说,访问http
接口可以,访问https
的接口不行,需要把下面reg
文件整理并且双击执行,让net 4
框架支持 TLS1.2
协议。
执行 net4下安装TLS1.2.reg
1 2 3 4 5 6 7
| Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319] "SchUseStrongCrypto"=dword:00000001
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319] "SchUseStrongCrypto"=dword:00000001
|
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| public class HttpHelper { public static string PostUrl(string url, string postData) { HttpWebRequest request = null; if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { request = WebRequest.Create(url) as HttpWebRequest; ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); request.ProtocolVersion = HttpVersion.Version11; ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; request.KeepAlive = false; ServicePointManager.CheckCertificateRevocationList = true; ServicePointManager.DefaultConnectionLimit = 100; ServicePointManager.Expect100Continue = false; } else { request = (HttpWebRequest)WebRequest.Create(url); }
request.Method = "POST"; request.ContentType = "text/plain"; request.Accept = "*/*";
byte[] data = Encoding.UTF8.GetBytes(postData); Stream newStream = request.GetRequestStream(); newStream.Write(data, 0, data.Length); newStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream stream = response.GetResponseStream(); string result = string.Empty; using (StreamReader sr = new StreamReader(stream)) { result = sr.ReadToEnd(); }
return result; }
private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; } }
|