The below code is for api call using restclient...But it is not getting response any one have idea about this?
var client = new RestClient("http://www.sentiment140.com");
var request = new RestRequest(Method.POST);
request.Resource = "api/bulkClassifyJson";
request.AddParameter("appid", "abcd#gmail.com");
request.RequestFormat = DataFormat.Json;
request.AddBody(text);
var response = client.Execute(request);
var serializer = new JavaScriptSerializer();
List<Sentimental> items = serializer.Deserialize<List<Sentimental>>(response.Content);
return items;
Related
var client = new RestClient("http://10.0.0.244:8885/terminal/info");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("apikey", "adasdsadasd");
var body = #"{}";
request.AddParameter("application/json", body, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
Could someone, please, help me write this code with HttpClient?
I try following code.
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://10.0.0.244:8885/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Clear();
HttpRequestMessage request = new HttpRequestMessage();
request.Method = HttpMethod.Post;
request.RequestUri = new Uri($"{client.BaseAddress}/terminal/info");
request.Headers.Add("apikey", "adasdsadasd");
var body = Newtonsoft.Json.JsonConvert.SerializeObject(new { });
request.Content = new StringContent(body, Encoding.UTF8, "application/json");//CONTENT-TYPE header
request.Content.Headers.Clear();
request.Content.Headers.ContentLength = 2;
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.SendAsync(request).GetAwaiter().GetResult();
var x = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
}
But it response with Status Code 400 (ParseError)
You can accomplish what you are trying to do with much less code. Also this should be in an async method. Below is an example
internal async Task<string> GetResponse()
{
using var client = new HttpClient();
client.BaseAddress = new Uri("http://10.0.0.244:8885/");
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Add("apikey", "adasdsadasd");
var content = new StringContent("{}", Encoding.UTF8, "text/plain");
var response = await client.PostAsync("/terminal/info", content);
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsStringAsync();
}
return null;
}
I try to access to the REST API from NetExplorer. It works when I send a request with postman :
But It doesn't with my C# code :
var client = new RestClient("https://patrimoine-click.netexplorer.pro/api/auth");
var ReqAuth = new { user = "xxxxxxxxxxxxxxxxxx", password = "xxxxxxxxxxxxx" };
JsonResult result = new JsonResult(ReqAuth);
var request = new RestRequest(result.ToString(), Method.Post);
request.AddHeader("Accept", "application/json");
RestResponse response = await client.ExecuteAsync(request);
Here's the error message :
{"error":"Il n'existe aucune m\u00e9thode de l'API pouvant r\u00e9pondre \u00e0 votre appel."}
In english, there's no API method to resolve your call
If somebody can help me ...
Thanks
You are using the constructor of RestRequest wrong, the constructor does not take in the content (body) like that. Try using it with AddJsonBody like so:
var client = new RestClient("https://patrimoine-click.netexplorer.pro/api/auth");
var ReqAuth = new { user = "xxxxxxxxxxxxxxxxxx", password = "xxxxxxxxxxxxx" };
var request = new RestRequest();
request.Method = RestSharp.Method.Post;
request.AddJsonBody(ReqAuth);
request.AddHeader("Accept", "application/json");
RestResponse response = await client.ExecuteAsync(request);
Documentation: https://restsharp.dev/usage.html#request-body
I am trying to call Rest API with content and headers in c#. Actually I am trying to convert to c# from Python code which is:
import requests
url = 'http://url.../token'
payload = 'grant_type=password&username=username&password=password'
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
response = requests.request('POST', url, headers = headers, data = payload, allow_redirects=False)
print(response.text)
So far I am trying with:
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(Url);
var tmp = new HttpRequestMessage
{
Method = HttpMethod.Post,
Content =
{
}
};
var result = client.PostAsync(Url, tmp.Content).Result;
}
I have no idea how to put from Python code Headers (Content-Type) and additional string (payload).
If you use RestSharp, you should be able to call your service with the following code snipped
var client = new RestClient("http://url.../token");
var request = new RestRequest(Method.POST);
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddParameter("application/x-www-form-urlencoded", "grant_type=password&username=username&password=password", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
var result = response.Content;
I based my answer on the anwser of this answer.
Here a sample I use in one of my apps:
_client = new HttpClient { BaseAddress = new Uri(ConfigManager.Api.BaseUrl),
Timeout = new TimeSpan(0, 0, 0, 0, -1) };
_client.DefaultRequestHeaders.Accept.Clear();
_client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
_client.DefaultRequestHeaders.Add("Bearer", "some token goes here");
using System.Net.Http;
var content = new StringContent("grant_type=password&username=username&password=password");
content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
client.PostAsync(Url, content);
Or use FormUrlEncodedContent without set header
var data = new Dictionary<string, string>
{
{"grant_type", "password"},
{"username", "username"},
{"password", "password"}
};
var content = new FormUrlEncodedContent(data);
client.PostAsync(Url, content);
If you write UWP application, use HttpStringContent or HttpFormUrlEncodedContent instead in Windows.Web.Http.dll.
using Windows.Web.Http;
var content = new HttpStringContent("grant_type=password&username=username&password=password");
content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
client.PostAsync(Url, content);
var data = new Dictionary<string, string>
{
{"grant_type", "password"},
{"username", "username"},
{"password", "password"}
};
var content = new FormUrlEncodedContent(data);
client.PostAsync(Url, content);
I wanted to know what kind of proxies are compatible with RestSharp and how to use them?
You can use System.Net WebProxy as below.
var request = new RestRequest(funcName, funcType);
request.RequestFormat = DataFormat.Json;
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json";};
request.AddBody(param);
RestClient restClient = new RestClient(url);
restClient.Proxy = new WebProxy(myProxyUrl, myProxyHost);
restClient.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
var value = restClient.Execute(request);
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 !
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);
This is old but I was just struggling with this too. This is the easiest way I found.
var client = new RestClient("http://myurl.com/api/");
var request = new RestRequest("getCatalog?token=saga001");
var response = client.Execute(request);
if (response.StatusCode == HttpStatusCode.OK)
{
// Two ways to get the result:
string rawResponse = response.Content;
MyClass myClass = new JsonDeserializer().Deserialize<MyClass>(response);
}
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);
If you want to save the result into JSON file:
You should use these namespaces:
using RestSharp;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
var client = new RestClient("http://myurl.com/api/");
var request = new RestRequest(Method.GET);
request.AddHeader("content-type", "application/json");
var queryResult = client.Execute<Object>(request).Data;
string json = JsonConvert.SerializeObject(queryResult);
System.IO.File.WriteAllText(#"C:\...\path.json", json);