#Encoding special characters in HTTP requests - c#

I'm trying to develop a console application to generate access token from Salesforce REST API using rest sharper library in C#. One of the request parameters is username which is of type user#username.com. I have tried to encode it. C# detects it the proper way after encoding it. But fiddler data is showing %20 instead of # for username.
Appreciate your input.
namespace Restsharper
{
class Program
{
static void Main(string[] args)
{
var client = new RestClient("https://xx--zz.mm.my.salesforce.com/services/oauth2/token");
RestRequest request = new RestRequest() { Method = Method.POST };
request.AddHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-16");
request.Parameters.Clear();
request.AddParameter("grant_type","password");
var pwd = Uri.EscapeUriString("Password#");
var userName = Uri.EscapeUriString("user#username.com");
request.AddParameter("password", pwd);
request.AddParameter("username", userName);
request.AddParameter("client_id","456fdas4fsdfsd4fds65uiryewiuryiuy43246FSDFSdasfcdasfasfFDF45_$rewrw#$$fFFFF");
request.AddParameter("client_secret","77554698412");
// request.RequestFormat("","");
var response = client.Execute(request);
}
}
}

Related

IRestResponse could not be found

I have restsharp 107.1.2 loaded via nuget target framework is .net 6.0. The following code claims that IRestResponse reference is missing, though I feel like I'm following pretty close to the RestSharp documentation. What am I missing?
using RestSharp;
using RestSharp.Authenticators;
using System.Text;
static void Main()
{
String url = "https://www.invoicecloud.com/api/v1/biller/status/";
//Set up the RestClient
var client = new RestClient(url);
//Store the generated API from the biller portal
String GeneratedAPIKey = "SomeKey=";
//Convert genrated API key to Base64
String encodedAPIKey = encoding(GeneratedAPIKey);
//HTTPBasicAuthentication will take a username and a password
//Here we use your API key as the username and leave the password with ""
client.Authenticator = new HttpBasicAuthenticator(encodedAPIKey, "");
//Get the request
var request = new RestRequest("resource", Method.Get);
//Get the response
// var response = client.ExecuteGetAsync(request);
IRestResponse reponse = client.Execute(request);
As per the documentation (https://restsharp.dev/v107/#restsharp-v107) ...
The IRestResponse interface is deprecated. You get an instance of RestResponse or RestResponse<T> in return.
https://restsharp.dev/v107/#deprecated-interfaces
Again, according to the documentation ...
var client = new RestClient("https://api.myorg.com");
var request = new RestRequest()
.AddQueryParameter("foo", "bar")
.AddJsonBody(someObject);
var response = await client.PostAsync<MyResponse>(request, cancellationToken);
... as an example.

How to add bearertoken to post/get restsharp automation testing

maybe anyone could help me with RestSharp api automation testing.
I'll try to be as clear as possible.
Basically the scheme is:
I'm sending my username/password credentials & I get BearerToken in return.
I parse the bearer token into a json file.
After I get the bearer token I need to "Authenticate" in order to get the information that I need.
For example i need full company credit report which I get after I input companyName ="Whatever"; companyCode = "Whatever";
{
var client = new RestClient("https://www.myapitesting.com/api/Auth/Authenticate");
var request = new RestRequest(Method.GET);
var body = new AuthenticatePostCredentials { Username = "myUserName", Password = "myPassword" };
request.AddJsonBody(body);
var response = client.Post(request);
HttpStatusCode statusCode = response.StatusCode;
int numericStatusCode = (int)statusCode;
request.AddHeader("content-type", "application/json");
var queryResult = client.Execute<object>(request).Data;
string jsonToken = JsonConvert.SerializeObject(queryResult);
var JSON1 = JToken.Parse(jsonToken);
var pureToken = JSON1.Value<string>("token");
File.WriteAllText(#"C:\Users\....\TestAPI\TestAPI\token.json", pureToken);
Console.WriteLine(pureToken);
Console.WriteLine(numericStatusCode)
The output I get is: token, status code 200 (correct credentials to get the bearertoken)
//////////At this point I get the token and it is writed into my json file/////////////// (the token works)
Now im trying to authenticate with my token and get the company information that I need
var client = new RestClient("https://www.myapitesting.com/api/GetCompanyReport");
var myRequest = new RestRequest(Method.POST);
myRequest.AddHeader("Accept", "application/json");
myRequest.AddHeader("Authorization", $"Bearer{pureToken}");
myRequest.AddHeader("content-type", "application/json");
var companyInfoInput = new AuthenticatePostCredentials { companyName = "MyCompanyName", companyCode = "MyCompanyCode" };
requestas.AddJsonBody(companyInfoInput);
var response = myRequest.Execute(request);
Console.WriteLine(response.Content);
The output I get is error code that says I havent authenticated, even though I pass the bearer token with my addHeader command.
{"ErrorId":401,"ErrorName":"Unauthorized","ErrorDescription":"User is not logged in"}
What am I doing wrong? Any kind of help would be greatly appreciated!
In this case, you could load the "Authenticator" you want to use, in the case of JWT you may instantiate something like this:
var authenticator = new JwtAuthenticator(pureToken);
and then set your client authenticator like this:
client.Authenticator = authenticator;
Mainly, you should not need to set headers by hand for the most commons ones using Restsharp.
You can for example fix this statement:
var myRequest = new RestRequest(url, DataFormat.Json);
var response = client.Post(request);
I also made this gist for you to check an example
If you want to see something more complete I also have this another gist

How do i call an API in c# with a api key

So i´ve recently tried working with an api for the first time and i really don´t know what to do with the this api: https://skinbaron.de/misc/apidoc/ .I have already looked tutorials on how to call an api in c# but i still don´t really get what i have to do in my specific case.
I´ve tried this: How do I make calls to a REST api using C#?
This question might seem stupid to people that know how to work with stuff like this but i have no expierence with api´s so far.
The exact code i´ve tried:
private const string URL = "https://api.skinbaron.de/";
private static string urlParameters = "?api_key=123"; // I have replaced the "123" with my apikey
static void Main(string[] args)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(URL);
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync(urlParameters).Result;
if (response.IsSuccessStatusCode)
{
// do something
}
else
{
Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
}
client.Dispose();
}
You can use Rest sharp. Its really easy to use. This is an third party library used in c# to manage API's. No need to bother with any of the other details used to call API's.
var client = new RestClient("https://api.skinbaron.de/GetBalance");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("Accept", "application/json");
request.AddParameter("apikey", "123");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
//Rest of the stuff
It looks like they're expecting you to POST rather than GET, and to pass a JSON object in the body of your POST, with "apikey" as a property on the JSON object.
Normally, in C# you would create a model class that you would then serialize for your post, but if all you have to post is the apikey I would just serialize a Dictionary object with your apikey as the only member of the collection.
For instance, I think this code might do what you want.
private const string URL = "https://api.skinbaron.de/";
private static string urlParameters = "?api_key=123"; // I have replaced the "123" with my apikey
private static string apiKey = "";
static void Main(string[] args)
{
using (var webClient = new WebClient()) {
webClient.Headers.Add(HttpRequestHeader.Accept, "application/json");
webClient.Headers.Add(HttpRequestHeader.ContentType, "application/json");
var postDictionary = new Dictionary<string, string>() {
{"apikey", apiKey}
};
var responseBody = webClient.UploadString(URL, JsonConvert.SerializeObject(postDictionary));
}
}

Problem calling the prediction endpoint uploading an image using rest sharp for the Microsoft custom vision API cognitive service

I am trying to upload an image to the Microsoft custom vision API prediction endpoint using Restsharp, I am trying to use the AddFile method but I am getting a BadRequest as the result, here is the code I am using
public IRestResponse<PredictionResponse> Predict(string imageFileName)
{
var file = new FileInfo(imageFileName);
var serviceUrl = ConfigurationManager.AppSettings["api.custom-vision.prediction.url.file"];
var serviceKey = ConfigurationManager.AppSettings["api.custom-vision.key"];
var client = new RestClient(serviceUrl);
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/octet-stream");
request.AddHeader("Prediction-Key", serviceKey);
request.AddFile(file.Name, file.FullName);
var response = client.Execute<PredictionResponse>(request);
return response;
}
When I execute the method I am getting the following response back from the service
{
"code": "BadRequestImageFormat",
"message": "Bad Request Image Format, Uri: 1062fe0480714281abe2daf17beb3ac5"
}
After looking for ways in the restsharp documentation to properly upload a file, I came to the solution that it needs to be passed as parameter with an array of bytes with the parameter type of ParameterType.RequestBody
Here is the example of the method that actually works
public IRestResponse<PredictionResponse> Predict(string imageFileName)
{
var file = new FileInfo(imageFileName);
var serviceUrl = ConfigurationManager.AppSettings["api.custom-vision.prediction.url.file"];
var serviceKey = ConfigurationManager.AppSettings["api.custom-vision.key"];
var client = new RestClient(serviceUrl);
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/octet-stream");
request.AddHeader("Prediction-Key", serviceKey);
request.AddParameter("content", File.ReadAllBytes(file.FullName), ParameterType.RequestBody);
var response = client.Execute<PredictionResponse>(request);
return response;
}

How Do You Download a Csv File With Restsharp Without Getting Logged Out?

Here is my code.
Now When I run the code, the output to my terminal from Console.WriteLine is correct and is what I want written in my csv file. However, when I check the example.csv file on my computer, it just has the html of the sign in page indicating that I was logged out. What is the problem here?
From my understanding using cookiejar allows me to store logins and should keep me logged in even with extra requests.
using System;
using RestSharp;
using RestSharp.Authenticators;
using RestSharp.Extensions;
namespace Updater
{
class ScheduledBilling
{
public static void report()
{
var client = new RestClient("http://example.com");
client.CookieContainer = new System.Net.CookieContainer();
client.Authenticator = new SimpleAuthenticator("username", "xxx", "password", "xxx");
var request = new RestRequest("/login", Method.POST);
client.DownloadData(new RestRequest("/file", Method.GET)).SaveAs("example.csv");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
}
}
class MainClass
{
public static void Main(string[] args)
{
string test = "\r\n";
ScheduledBilling.report();
Console.Write(test);
}
}
}
Also another small related question. Why does it execute and produce in the terminal the new rest request in client.DownloadData when response refers to the original log-in request?
You didn't execute the login request before trying to download the CSV. Your code should look something like this:
public static void report()
{
//Creates the client
var client = new RestClient("http://example.com");
client.CookieContainer = new System.Net.CookieContainer();
client.Authenticator = new SimpleAuthenticator("username", "xxx", "password", "xxx");
//Creates the request
var request = new RestRequest("/login", Method.POST);
//Executes the login request
var response = client.Execute(request);
//This executes a seperate request, hence creating a new requestion
client.DownloadData(new RestRequest("/file", Method.GET)).SaveAs("example.csv");
Console.WriteLine(response.Content);
}

Categories

Resources