今天修改了一下自己以前写的程序,然而在POST数据时却发生了“基础链接已关闭”的奇怪BUG,调试了半天也没有发现原因。
Dim request As HttpWebRequest = WebRequest.Create("https://xxxxxxx/api")
request.Proxy = Nothing    '关闭代理,否则速度巨慢无比
request.Method = "POST"

Dim postdata As String = "POST数据..."
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postdata)
request.ContentType = "application/x-www-form-urlencoded"
request.ContentLength = byteArray.Length
Dim dataStream As Stream = request.GetRequestStream() '在这里发生错误
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()

Dim response As HttpWebResponse = request.GetResponse()    
' ...
后来Google了半天,发现可能是默认的安全协议类型 SecurityProtocolType 错误,
因为我这个程序使用的是.net 2.0的环境,其默认的 SecurityProtocolTypessl3+tls1.0协议。
然而这两个协议早已经不安全,所以目前大部分的网站都已不支持这两个协议!
然而.net 2.0的 SecurityProtocolType 的枚举类型中并没有其他协议的参数,只好由我自己查询枚举值,再手动设置到 ServicePointManager.SecurityProtocolType 的全局属性之中了!
' 因为此属性乃是全局属性,只需在使用WebRequest前执行此代码即可
Net.ServicePointManager.SecurityProtocol = 48 Or 192 Or 768 Or 3072 'Ssl3 Tls Tls1.1 Tls1.2

' 貌似用这个参数可以使用系统内最新的安全协议?
Net.ServicePointManager.SecurityProtocol = 2147483647
' .net 4.7以上采用的是系统默认,似乎也是最新的安全协议?
Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.SystemDefault
如果还是发生错误,或者用户的机器显示无效的安全协议,表明该机器需要更新.NET框架补丁:
https://support.microsoft.com/zh-cn/help/3154518/support-for-tls-system-default-versions-included-in-the-net-framework