Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get JSON response using RestSharp

I'm new to C# and I'm trying to get the JSON response from a REST request using RestSharp; The request I want to execute is the following one : "http://myurl.com/api/getCatalog?token=saga001". It works great if I'm executing it in a browser.

I've tried this :

var client = new RestClient("http://myurl.com/api/");

var request = new RestRequest("getCatalog?token=saga001"); 

var queryResult = client.Execute(request);

Console.WriteLine(queryResult);

And I get "RestSharp.RestReponse" instead of the JSON result I'm hopping for.

Thanks for your help !

like image 357
Adrien Budet Avatar asked Apr 15 '14 14:04

Adrien Budet


People also ask

How do you get a RestSharp response?

var client = new RestClient("http://myurl.com/api/"); var request = new RestRequest("getCatalog? token=saga001"); var queryResult = client. Execute(request); Console. WriteLine(queryResult);

Is RestSharp better than HTTP client?

The main conclusion is that one is not better than the other, and we shouldn't compare them since RestSharp is a wrapper around HttpClient. The decision between using one of the two tools depends on the use case and the situation.

How can I put my body in my RestSharp?

RestSharp supports sending XML or JSON body as part of the request. To add a body to the request, simply call AddJsonBody or AddXmlBody method of the IRestRequest instance. There is no need to set the Content-Type or add the DataFormat parameter to the request when using those methods, RestSharp will do it for you.


2 Answers

Try:

var client = new RestClient("http://myurl.com/api/");

var request = new RestRequest("getCatalog?token={token}", Method.GET); 

request.AddParameter("token", "saga001", ParameterType.UrlSegment);   

// request.AddUrlSegment("token", "saga001"); 

request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };

var queryResult = client.Execute(request);

Console.WriteLine(queryResult.Content);
like image 141
chridam Avatar answered Oct 20 '22 06:10

chridam


Try as below:

var client = new RestClient("http://myurl.com/api/");

client.ClearHandlers();
var jsonDeserializer = new JsonDeserializer();
client.AddHandler("application/json", jsonDeserializer);

var request = new RestRequest("getCatalog?token=saga001"); 

var queryResult = client.Execute(request);

Console.WriteLine(queryResult);
like image 21
aaron ngo Avatar answered Oct 20 '22 06:10

aaron ngo