【问题标题】:RestClient works but HttpWebRequest doesn'tRestClient 有效,但 HttpWebRequest 无效
【发布时间】:2025-12-20 13:15:10
【问题描述】:

此代码有效:

 var source = "https://jade.io/xml/au-qld-dc.xml";
        
 var client = new RestClient(source);
 var request = new RestRequest(Method.GET);
 IRestResponse resp = client.Execute(request);
 Console.WriteLine(resp.Content);

xml 被检索并显示在控制台中。 但是这段代码不起作用:

HttpWebRequest httpsRequest = (HttpWebRequest) WebRequest.Create(source);
httpsRequest.Method = "GET";
var response = httpsRequest.GetResponse();

它会引发 403(禁止)错误...

我想知道为什么它不起作用,因为我有一些使用 WebRequest 的遗留代码,并且在用 RestClient 替换所有代码之前,如果有一个简单的修复...

【问题讨论】:

  • 例如,我认为RestClient会添加默认的User-Agent头,而HttpWebRequest不会。
  • 您可以使用网络嗅探器(例如 Wireshark 或 Fiddler)来检查两个 http 调用之间的差异。用它来纠正问题。

标签: c# webrequest


【解决方案1】:

添加 UserAgent 标头,它将起作用。

var source = "https://jade.io/xml/au-qld-dc.xml";
HttpWebRequest httpsRequest = (HttpWebRequest)WebRequest.Create(source);
httpsRequest.Method = "GET";
httpsRequest.UserAgent = "Test";
var response = httpsRequest.GetResponse();

【讨论】:

  • 谢谢,现在可以使用了!但奇怪的是它不适用于此 UserAgent:“Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36";你知道为什么吗?
最近更新 更多