【问题标题】:C# RestSharp get request failedC# RestSharp 获取请求失败
【发布时间】:2022-07-18 22:18:40
【问题描述】:

我正在尝试使用 C# RestSharp 发送 GET 请求,如下所示。

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var client = new RestClient("https://www.futureelectronics.cn/p/2052120");
client.Timeout = -1;
var request = new RestRequest(Method.GET);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);

此代码无法使用超时。

但 python 相同的代码运行良好。

import requests

url = "https://www.futureelectronics.cn/p/2052120"

payload={}
headers = {}

response = requests.request("GET", url, headers=headers, data=payload)

print(response.text)

这个错误的原因是什么? 谢谢。

【问题讨论】:

  • 有异常吗?
  • 这表明您的 URL 不正确,或者被阻止。您是否在与 Python 代码相同的 PC 上运行 C# 代码?如果不设置 Tls12 会怎样?如果从命令行尝试 cURL 会发生什么?
  • 是的。也不例外

标签: python c# timeout restsharp


【解决方案1】:

我建议在 try catch 块中尝试它,看看是否产生了错误,这可以阐明原因。 如果你的目标拒绝使用 Tls12,我还建议交换:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

为:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 |安全协议类型.Tls |安全协议类型.Tls11 |安全协议类型.Tls12;

另一件事,我发现添加: ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);

还帮助我找到了问题。

所以:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
var client = new
RestClient("https://www.futureelectronics.cn/p/2052120");
client.Timeout = -1;
var request = new RestRequest(Method.GET);
try
{
    IRestResponse response = client.Execute(request);
}
catch (Exception ex)
{
    Console.WriteLine("Caught exception : " + ex.message)
}
Console.WriteLine(response.Content);

这对你有什么影响?

【讨论】:

  • 嗨,布莱恩。谢谢你的建议。但它也不起作用。它总是发生超时错误。没有例外。
【解决方案2】:

请尝试在执行行之前添加以下行。我发现它需要 TLS12;

System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-10
    • 2016-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多