Restsharp get text Files from Server - c#

I'm new to Restsharp. I got a client request and in these "Files" are ten text files.
With this request, I want to return all file names shown in my console, but when I run it, the console is still empty and I don't know why...
Maybe someone can help me :)
var client = new RestClient("http://localhost:12345/files/");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Authorization", "Bearer");
request.AddParameter("application/json", "{\n\n\t\"Username\": \"" + username + "\",\n\t\"Password\": \"" + password + "\",\n\t\"DeviceID\": \"Test\"\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);

Related

I want to Receive Webhook Response at My .Net C# WPF application.Sending requests from same WPF application response at https://webhook.site/

TerminalAPIRequest terminalAPIRequest = new TerminalAPIRequest();
TerminalAPIResponse terminalAPIResponse = new TerminalAPIResponse();
var client = new RestClient("https://connect.squareupsandbox.com/v2/terminals/checkouts");
//client.Timeout = -1;
var request = new RestRequest("https://connect.squareupsandbox.com/v2/terminals/checkouts", Method.Post);
request.AddHeader("Square-Version", "2023-01-19");
request.AddHeader("Authorization", "Bearer token");
request.AddHeader("Content-Type", "application/json");
var body = JsonConvert.SerializeObject(terminalAPIRequest);
request.AddParameter("application/json", body, ParameterType.RequestBody);
var response = client.Execute(request);
Related Webhook Responses are found at webhook.site
. Now How can I get that response to My WPF application?

401.0000007 Error while trying to get the DHL Interface C# code. Followed DHL document

I have been trying to connect to DHL interface but i cannot get the token access key from C# code. here is my current code. Please let me know if you have a solution -
RestClient client = new RestClient();
client.ClearHandlers();
client.Timeout = -1;
client.BaseUrl = new Uri("https://api-sandbox.dhlecs.com/auth/v4/accesstoken");
client.Authenticator = new HttpBasicAuthenticator(ConfigurationManager.AppSettings["DHLClientId"], ConfigurationManager.AppSettings["DHLClientSecret"]);
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("Accept", "application/json");
request.Parameters.Clear();
request.AddParameter("grant_type", "client_credentials");
IRestResponse response = client.Execute(request);
var local = response.Content.ToString();
if (response.StatusCode == HttpStatusCode.OK)
{
return response.Content.ToString();
}
else
{
throw new Exception($#"Unable to authorize with GLS. Contact IT");
}
here is the error i get -
https://api-sandbox.dhlecs.com/docs/errors/401.0000007"
>> Solution :
this needs to be removed -
request.Parameters.Clear();

How to get admin token in magento 2.1.8?

I'm trying to get an admin token from Magento version 2.1.8 in c# using well-known code that works for all except me. Could not understand where is the problem.
In response I get:
ErrorException = null, Content= "{\" message \ ": \" Request does not match any path. \ ", \" trace \ ": null}"
public Magento(string magentoUrl)
{
//Relative URL needs to be Specified
var endpoint = "/rest/V1/integration/admin/token";
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var _restClient = new RestClient(magentoUrl);
var request = new RestRequest(endpoint, Method.POST);
//Initialize Credentials Property
var userRequest = new Credentials { username = "reewrew", password = "rwerwerw" };
var inputJson = JsonConvert.SerializeObject(userRequest);
//Request Header
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Accept", "application/json");
//Request Body
request.AddParameter("application/json", inputJson, ParameterType.RequestBody);
var response = _restClient.Execute(request);
var token = response.Content;
}
I found the problem. I use HTTP instead of HTTPS in URL.

How to call a httpClient request - response is giving decoded value

I have used postman to send a post request by attaching a file in the request body. Below is the postman request sample. I got success response with the response content.
var client = new RestClient("https://***********");
var request = new RestRequest(Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("Connection", "keep-alive");
request.AddHeader("Content-Length", "757");
request.AddHeader("Accept-Encoding", "gzip, deflate");
request.AddHeader("Host", "**********");
request.AddHeader("Postman-Token", "********");
request.AddHeader("Cache-Control", "no-cache");
request.AddHeader("Accept", "*/*");
request.AddHeader("User-Agent", "PostmanRuntime/7.18.0");
request.AddHeader("Authorization", "Bearer XX");
request.AddHeader("Content-Type", "multipart/form-data");
request.AddHeader("content-type", "multipart/form-data; boundary=----WebKitFormBoundaryabc");
request.AddParameter("multipart/form-data; boundary=----WebKitFormBoundaryabc", "------WebKitFormBoundaryabc\r\nContent-Disposition: form-data; **name=\"\"**; filename=\"sample.csv\"\r\nContent-Type: text/csv\r\n\r\n\r\n------WebKitFormBoundaryabc--", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Actual expected response from api call using postman is:
IssussessStatusCode: true{ ResponseData { file Name : "sample", readable :true} }
I have used C# httpClient method as below to do the same call
using (var _httpClient = new HttpClient())
{
using (var stream = File.OpenRead(path))
{
_httpClient.DefaultRequestHeaders.Accept.Clear();
_httpClient.DefaultRequestHeaders.Add("Accept", "*/*");
_httpClient.DefaultRequestHeaders.Add("cache-control", "no-cache");
_httpClient.DefaultRequestHeaders.Add("Accept-Encoding", "gzip, deflate");
_httpClient.DefaultRequestHeaders.Add("Host", "*********");
_httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer XX");
_httpClient.DefaultRequestHeaders
.Accept
.Add(new MediaTypeWithQualityHeaderValue("multipart/form-data")); // ACCEPT header
var content = new MultipartFormDataContent();
var file_content = new ByteArrayContent(new StreamContent(stream).ReadAsByteArrayAsync().Result);
file_content.Headers.ContentType = new MediaTypeHeaderValue("text/csv");
file_content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
FileName = "sample.csv",
**Name = " ", // Is this correct. In postman request it is **name=\"\"****
};
content.Add(file_content);
_httpClient.BaseAddress = new Uri("**************");
var response = await _httpClient.PostAsync("****url", content);
if (response.IsSuccessStatusCOde)
{
string responseBody = await response.Content.ReadAsStringAsync();
}
}
}
I am getting tresponse this way
Result: "\u001f�\b\0\0\0\0\0\u0004\0�\a`\u001cI�%&/m�{\u007fJ�J��t�\b�`\u0013$ؐ#\u0010������\u001diG#)�*��eVe]f\u0016#�흼��{���{���;�N'���?\\fd\u0001l��J�ɞ!���\u001f?~|\u001f?\"~�G�z:͛�G�Y�䣏��\u001e�⏦�,�������G\vj�]�_\u001f=+�<����/��������xR,�����4+�<�]����i�q��̳&O���,�\u0015��y�/۴�/�����r�������G��͊�pX������\a�\u001ae_�\0\0\0"
Here I get some decoded values when I execute `response.Content.ReadAsStringAsync();`
Can someone help me on what needs to be done here?
Ok , i understand your problem. The api is returning response in a compressed format. You need to Deflate/Gzip it. I have faced similar problems earlier. Try my solution.
You need to make use of the HttpClientHandler() class like this.
var httpClientHandler = new HttpClientHandler()
{
AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip
};
_httpClient = new HttpClient(httpClientHandler);
When the httpClient gets instantiated, you need to pass in the handler in the first place.

Upload file to OneDrive using RestAPI

I am trying to upload an image to OneDrive using below code. The file was successfully uploaded to the OneDrive folder but when I download the file manually from OneDrive, it opens in black color and shows Invalid Image.
var client = new RestClient("https://graph.microsoft.com/v1.0" + $"/drives/{driveID}/items/{folderId}:/{originalFileName}:/content");
var request = new RestRequest(Method.PUT);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("Content-Type", Path.GetExtension(originalFileName).GetMimeType());
request.AddHeader("Authorization", "Bearer " + GetAccessToken());
request.AddFile("content", System.IO.File.ReadAllBytes(filePath), originalFileName);
var response = client.Execute(request);
I really do not know what mistake I am making in here. May you please help me?
Inspired from this SO answer
I need to change it to HttpClient from RestClient. After change the code will like:
using (var client = new HttpClient())
{
var url = "https://graph.microsoft.com/v1.0" + $"/drives/{driveID}/items/{folderId}:/{originalFileName}:/content";
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + GetAccessToken());
byte[] sContents = System.IO.File.ReadAllBytes(filePath);
var content = new ByteArrayContent(sContents);
var response = client.PutAsync(url, content).Result.Content.ReadAsStringAsync().Result;
}

Categories

Resources