RestSharp proxy http/https/socks information - c#

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);

Related

Access a REST API with C#

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

RestClient works but HttpWebRequest doesn't

This code works:
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);
The xml is retrieved and displayed in the Console.
But this code doesn't work:
HttpWebRequest httpsRequest = (HttpWebRequest) WebRequest.Create(source);
httpsRequest.Method = "GET";
var response = httpsRequest.GetResponse();
It throws a 403 (Forbidden) error...
I'd like to know why it doesn't work, because I have some legacy code using WebRequest, and before replacing all that code with RestClient, if there is an easy fix...
Add UserAgent header and it will work.
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();

Can not upload Transient Document to Adobe Sign in C#

I'm trying to upload a transient document file to Adobe Sign in C#, and it has driven me to my wits end trying to get it to work.
I've even contacted Adobe, and even they don't know how to do it.
My code is as follows:
if (!File.Exists(#"documents\1-Registration Form.pdf"))
{
return;
}
Models objGetData = new Models();
RestClient objClient = new RestClient("https://api.na1.echosign.com:443/api/rest/v5");
RestRequest objRequest = new RestRequest("transientDocuments", Method.POST);
objRequest.AddFile("file", File.ReadAllBytes(#"documents\1-Registration Form.pdf"), "1-Registration Form.pdf");
objRequest.AddHeader("Access-Token", "-My Token Here-");
objRequest.RequestFormat = DataFormat.Json;
IRestResponse objResponse = objClient.Execute(objRequest);
var content = objResponse.Content;
JObject jsonLinq = JObject.Parse(content);
try
{
var objResultObjects = AllData(jsonLinq).First(c => c.Type == JTokenType.Array && c.Path.Contains("libraryDocumentList")).Children<JObject>();
}
catch(Exception ex)
{
ex.LogExceptionToDatabase();
}
return;
Here's the response that I'm getting as the result of my most recent attempt:
"{\"code\":\"NOT_FOUND\",\"message\":\"Resource not found\"}"
I typically get Bad request saying the file isn't present or a not found error, but they're not always the same.
All help will be appreciated.
EDIT:
The following code will give a response with a list of library docs so I know it's not the URL.
var objGetData = new Models();
var objClient = new RestClient("https://api.na1.echosign.com:443/api/rest/v5");
var objRequest = new RestRequest("libraryDocuments", Method.GET);
objRequest.AddHeader("Access-Token", "- My Key -");
objRequest.RequestFormat = DataFormat.Json;
objRequest.AddBody(objGetData);
IRestResponse objResponse = objClient.Execute(objRequest);
var content = objResponse.Content;
JObject jsonLinq = JObject.Parse(content);
SOLUTION:
var objClient = new RestClient(#"https://api.na1.echosign.com:443/api/rest/v5/");
var objRequest = new RestRequest(#"transientDocuments", Method.POST);
var thisFile = File.ReadAllBytes( #"documents\1-Registration Form.pdf");
objRequest.AddFile("File", File.ReadAllBytes( #"documents\1-Registration Form.pdf"), "1-Registration Form.pdf");
objRequest.AddHeader("Access-Token", "-MyToken-");
objRequest.RequestFormat = DataFormat.Json;
IRestResponse objResponse = objClient.Execute(objRequest);
var content = objResponse.Content;
JObject jsonLinq = JObject.Parse(content);
This did it. Apparently "file" is bad but "File" is okay.
var objClient = new RestClient(#"https://api.na1.echosign.com:443/api/rest/v5/");
var objRequest = new RestRequest(#"transientDocuments", Method.POST);
var thisFile = File.ReadAllBytes( #"documents\1-Registration Form.pdf");
objRequest.AddFile("File", File.ReadAllBytes( #"documents\1-Registration Form.pdf"), "1-Registration Form.pdf");
objRequest.AddHeader("Access-Token", "-MyToken-");
objRequest.RequestFormat = DataFormat.Json;
IRestResponse objResponse = objClient.Execute(objRequest);
var content = objResponse.Content;
JObject jsonLinq = JObject.Parse(content);
Not sure if the URI is correct, check missing '/' on the end of the RestClient (shouldn't be needed but still).
Lastly if you browse to the location in Angular 1 does it give you the same issue? I ask as this is a lot lighter to test and you can see using F12 developer tools exactly what is coming back from the open https channel.

Sentiment140 in Restclient Not working

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;

RestSharp - Authorization Header not coming across to WCF REST service

I am trying to call a locally hosted WCF REST service over HTTPS with basic auth.
This works and the Authorization header comes thru just fine and all is happy:
ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertficate;
var request = (HttpWebRequest)WebRequest.Create("https://localhost/MyService/MyService.svc/");
request.Method = "GET";
request.ContentType = "application/json";
request.Headers.Add(
System.Net.HttpRequestHeader.Authorization,
"Basic " + this.EncodeBasicAuthenticationCredentials("UserA", "123"));
WebResponse webResponse = request.GetResponse();
using (Stream webStream = webResponse.GetResponseStream())
{
if (webStream != null)
{
using (StreamReader responseReader = new StreamReader(webStream))
{
string response = responseReader.ReadToEnd();
}
}
}
When I try to use RestSharp however, the Authorization header never comes thru on the request:
ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertficate;
var credentials = this.EncodeBasicAuthenticationCredentials("UserA", "123");
var client = new RestSharp.RestClient("https://localhost/MyService/MyService.svc/");
var restRq = new RestSharp.RestRequest("/");
restRq.Method = Method.GET;
restRq.RootElement = "/";
restRq.AddHeader("Authorization", "Basic " + credentials);
var restRs = client.Execute(restRq);
What am i doing wrong with the RestSharp method?
I know that the AddHeader method works because this:
restRq.AddHeader("Rum", "And Coke");
will come thru, only "Authorization" seems stripped out/missing.
instead of adding the header 'manually' do the following:
var client = new RestSharp.RestClient("https://localhost/MyService/MyService.svc/");
client.Authenticator = new HttpBasicAuthenticator("UserA", "123");
I used milano's answer to get my REST service call to work (using GET)
Dim client2 As RestClient = New RestClient("https://api.clever.com")
Dim request2 As RestRequest = New RestRequest("me", Method.GET)
request2.AddParameter("Authorization", "Bearer " & j.access_token, ParameterType.HttpHeader)
Dim response2 As IRestResponse = client2.Execute(request2)
Response.Write("** " & response2.StatusCode & "|" & response2.Content & " **")
The key was making sure there was a space after the word 'Bearer' but this may apply to any type of custom token authorization header
You have to use ParameterType.HttpHeader parameter:
request.AddParameter("Authorization", "data", ParameterType.HttpHeader);
I was able to get the response from my rest API using this piece of code:
My API was returning server error and I used:
request.AddHeader("Authorization", $"Bearer {accessToken}");
var request = new RestRequest("/antiforgerytokensso", Method.Get);
restClient.Authenticator = new JwtAuthenticator(accessToken);
var response = await restClient.ExecuteAsync(request);
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));

Categories

Resources