215 字 ~ 1 分钟阅读

场景:浏览器可访问 URL,但使用 HttpWebRequest 请求网页内容报错(“基础连接已关闭/无法连接到远程服务器”)。

示例代码

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
public static bool CreateHTMLPage(string savePath, string url, string fileName)
{
if (!Directory.Exists(savePath))
{
Directory.CreateDirectory(savePath);
}

var fullPath = Path.Combine(savePath, fileName);
if (File.Exists(fullPath))
{
File.Delete(fullPath);
}

try
{
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = WebRequestMethods.Http.Get;
request.UserAgent = "Mozilla/5.0";
request.Accept = "*/*";
request.ContentType = "text/html";

using var response = (HttpWebResponse)request.GetResponse();
using var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
var content = reader.ReadToEnd();

File.WriteAllText(fullPath, content, Encoding.UTF8);
return true;
}
catch
{
if (File.Exists(fullPath))
{
File.Delete(fullPath);
}
throw;
}
}

常见原因与排查

  1. 防火墙或端口限制。
  2. 服务器网络不可达(在服务器上用浏览器或 curl 访问同一 URL)。
  3. TLS 版本不匹配(旧版 .NET 默认协议较低):
1
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
  1. 代理或 DNS 配置问题。