遇到Https网站,c# http请求的时候,总是报SSL连接错误。后来经搜索,发现有解决方案:
.net 2.0 需要引入一个第三方组件:BouncyCastle.dll,这是我写的一个例子:
public static string RequestWebServerByTCP(Uri uri, string method, NameValueCollection parameter, string cookie, Encoding encoding) { try { StringBuilder RequestHeaders = new StringBuilder(); RequestHeaders.Append(method + " " + uri.PathAndQuery + " HTTP/1.1\r\n"); method = method.ToUpper(); if (method == POSTMETHOD) RequestHeaders.Append("Content-Type:application/x-www-form-urlencoded\r\n"); RequestHeaders.Append("User-Agent:Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11\r\n"); RequestHeaders.Append("Cookie:" + cookie + "\r\n"); RequestHeaders.Append("Accept:*/*\r\n"); RequestHeaders.Append("Host:" + uri.Host + "\r\n"); byte[] postdata = null; StringBuilder sb = new StringBuilder(); if (method == GETMETHOD) { uri = GetMethodQueryString(uri, parameter, encoding); } else if (method == POSTMETHOD) { if (parameter != null) { foreach (string key in parameter) { sb.Append(string.Format(FORMATSTR1, System.Web.HttpUtility.UrlEncode(key, encoding), System.Web.HttpUtility.UrlEncode(parameter[key], encoding))); } } if (sb.Length != 0) { sb = sb.Remove(sb.Length - 1, 1); } postdata = encoding.GetBytes(sb.ToString()); RequestHeaders.Append("Content-Length:" + postdata.Length + "\r\n"); } RequestHeaders.Append("Connection:close\r\n\r\n"); byte[] req = Encoding.UTF8.GetBytes(RequestHeaders.ToString() + sb.ToString()); int port = 443; MyTlsClient client = new MyTlsClient(); var protocol = OpenTlsConnection(uri.Host, port, client); Stream tlsStream = protocol.Stream; tlsStream.Write(req, 0, req.Length); tlsStream.Flush(); StreamReader reader = new StreamReader(tlsStream); String line; StringBuilder html = new StringBuilder(); string firstLine = ""; int i = 0; while ((line = reader.ReadLine()) != null) { if (i == 0) { firstLine = line; i++; } html.AppendLine(line); if (line.Contains("