I am trying to make a simple request to get the html of a website but restsharp doesn't return any response in the 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
}
}
}
Two things:
when creating the IRestREquest - you need to pass in an enum value - NOT a string:
var request = new RestRequest(Method.GET);
A string would be interpreted as a resource to fetch - and not surprisingly, there's nothing to fetch at https://google.com/Method.GET
....
all of your HTTP headers must NOT contain a trailing :
request.AddHeader("Accept-Encoding", "gzip, deflate, br");
**** absolutely NO colon here!
So try this code:
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();
}
Suggestion: once you've made the call and received the response - check to see if it's successful. Since if it wasn't successful (for whatever reason), there's no point in trying to deserialize or work with the response anyway.....
IRestResponse response = client.Execute(request);
if (response.IsSuccessful)
{
// do your stuff here
}