c# - Https GET 请求在 Postman 和浏览器中通过但在代码中失败

标签 c# ssl httpwebrequest

我正在尝试通过使用 .Net 4.5 的 rest API 获取 JSON
我在代码中尝试了各种方法,但最终我得到了:

"Authentication failed because the remote party has closed the transportstream" .


完全相同的 URL 通过浏览器和 Postman 工作。
到目前为止,我已经尝试过使用 .Net 的 WebClient、HttpClient 和 HttpWebRequest 并获得相同的结果。我尝试比较 Postman 和我的代码之间的请求(通过 RequestBin),但即使它们相同,我仍然会不断返回:

Authentication failed because the remote party has closed the transport


我当前的代码使用的是 HttpWebRequest,但每个解决方案都可以。
我玩过所有的安全协议(protocol),其中一些会导致 API 返回 404有些会导致服务器返回

"Authentication failed because the remote party has closed the transport stream".


这是我当前的代码:
public string GetCityStreets()
{
    var url = "https://data.gov.il/api/action/datastore_search?resource_id=a7296d1a-f8c9-4b70-96c2-6ebb4352f8e3&q=26";
    var request = (HttpWebRequest)WebRequest.Create(url);
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 |
                                           SecurityProtocolType.Tls12 |
                                           SecurityProtocolType.Tls11 |
                                           SecurityProtocolType.Tls;

    var response = (HttpWebResponse)request.GetResponse();
    string jsonResponse;

    using (var reader = new StreamReader(response.GetResponseStream()))
    {
         jsonResponse = reader.ReadToEnd();
    }
    return jsonResponse;
}
在我当前的代码中,实际发出请求时会引发异常:request.GetResponse() .
本质上,我需要的是从 API 中获取 JSON。

最佳答案

设置 SecurityProtocolType.Tls12 之前 你初始化请求:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12` 
var request = WebRequest.CreateHttp(url);

如果您使用的是 Windows 7。在 Windows 10 上,您应该只需要 SecurityProtocolType.SystemDefault .

备注 : 启用 TLS1.3 (它在 Windows 7 和 Windows 10 中都可用),如果你不使用 .Net 4.8.Net Core 3.0 ,因为它没有枚举器,你可以设置它:
var secProtoTls13 = (SecurityProtocolType)12288;

删除所有其他 SecurityProtocolType你已经设置好了。

设置User-Agent标题也是强制性的,否则您将收到 404 (未找到)。这是 FireFox header :
request.UserAgent = "Mozilla/5.0 (Windows NT 10; Win64; x64; rv:65.0) Gecko/20100101 Firefox/65.0";

关于 User-Agent header 的注释 : 此特定站点未激活 HTTP Strict Transport Security (HSTS)。但是有些站点会这样做,当他们看到 WebBrowser 支持它时。 HttpWebRequest不理解它,所以它只会等待永远不会出现的响应,因为站点正在等待交互。
您可能想使用 IE11而是标题。

还要添加这个其他标题:
 request.Headers.Add(HttpRequestHeader.CacheControl, "no-cache");

关于c# - Https GET 请求在 Postman 和浏览器中通过但在代码中失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57202556/

相关文章:

c# - Web 服务和浏览器调用同步

c# - 是否可以模拟数据库事务参数?

c# - 在 C# 中重写泛型方法

php - 为 SSL 配置 cURL

Apache HTTP 客户端 javax.net.ssl.SSLPeerUnverifiedException : peer not authenticated

node.js - Docker AWS 证书管理器 SSL NodsJS 失败

c# - HttpWebRequest:无法为 SSL 建立信任关系 - 自签名证书已添加到受信任的根 CA

c# - 在 Unity 中使用 Shells 技术实现 Fur

c# - Task.WaitAll 抛出 OperationCanceledException

HTTP 请求偶尔没有到达服务器。为什么?