restsharp 响应不包含任何内容

restsharp response contains nothing

我正在尝试发出一个简单的请求以获取网站的 html,但 restsharp return 在 response.Content:

中没有任何响应
using System;
using RestSharp;

namespace AMD
{
    class Program
    {
        static void Main(string[] args)
        {
            string response2;
            
            var client = new RestClient("https://google.com");
            var request = new RestRequest("Method.GET");
            
            request.AddHeader("Host:", "google.com");
            request.AddHeader("User-Agent:", "Mozilla/5.0 (Windows NT 10.0; Win64; x64;");
            request.AddHeader("Accept:", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
            request.AddHeader("Accept-Language:", "en-US,en;q=0.5");
            request.AddHeader("Accept-Encoding:", "gzip, deflate, br");
            request.AddHeader("Connection:", "keep-alive");
            request.AddHeader("Cache-Control:", "max-age=0");

            IRestResponse response = client.Execute(request);
            
            response2 = response.Content.ToString();
            
            Console.WriteLine(response2);     // doesn't print anything
            
            Console.ReadLine();               // so console doesn't close
        }
    }
}

两件事:

  • 创建 IRestREquest 时 - 您需要传入一个 enum 值 - NOT 一个字符串:

    var request = new RestRequest(Method.GET);
    

    字符串将被解释为要获取的 资源 - 毫不奇怪,在 https://google.com/Method.GET ....

    处没有任何可获取的内容
  • 所有 的 HTTP headers 不得 包含尾随 :

    request.AddHeader("Accept-Encoding", "gzip, deflate, br");
                                    **** absolutely NO colon here! 
    

所以试试这个代码:

 static void Main(string[] args)
 {
     string response2;

     var client = new RestClient("https://google.com");
     var request = new RestRequest(Method.GET);

     request.AddHeader("Host", "google.com");
     request.AddHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64;");
     request.AddHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
     request.AddHeader("Accept-Language", "en-US,en;q=0.5");
     request.AddHeader("Accept-Encoding", "gzip, deflate, br");
     request.AddHeader("Connection", "keep-alive");
     request.AddHeader("Cache-Control", "max-age=0");

     IRestResponse response = client.Execute(request);

     response2 = response.Content.ToString();

     Console.WriteLine(response2);     // doesn't print anything

     Console.ReadLine();
 }

建议:一旦您拨打电话并收到回复 - 检查看看是否成功。因为如果它不成功(无论出于何种原因),无论如何都没有必要尝试反序列化或使用响应......

IRestResponse response = client.Execute(request);

if (response.IsSuccessful)
{
    // do your stuff here
}