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

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

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?

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

How to convert C# RestSharp to C# ASP.NET httpclient

below codes is the generated c# restsharp codes from postman. How can I convert it to c# asp.net mvc4 codes for httpclient. When trying to debug in VS, I always have error of bad request. This is for ebay api creating a shipping fulfillment. Tested in postman works with the codes below.
var client = new RestClient("https://api.ebay.com/sell/fulfillment/v1/order/23-00000-11313/shipping_fulfillment");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Content-Language", "en-US");
request.AddHeader("Accept-Language", "en-US");
request.AddHeader("Accept-Charset", "utf-8");
request.AddHeader("Accept", "application/json");
request.AddHeader("Authorization", "Bearer v^1.1#i^1#I^3#f^0#p^3#r^0#t^H4sIAAAAA==");
request.AddParameter("application/json", "{\"lineItems\":[{\"lineItemId\":\"10022882297723\",\"quantity\":1}],\"shippedDate\":\"2020-02-11T01:28:16.475Z\",\"shippingCarrierCode\":\"Couriers Please\",\"trackingNumber\":\"UHV3436755010009000000\"}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
Current codes in asp.net but having error bad request.
private HttpClient CreateHttpClient()
{
var client = new HttpClient();
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
string baseAddress = WebApiBaseAddress;
if (string.IsNullOrEmpty(baseAddress))
{
throw new HttpRequestException("There is no base address specified in the configuration file.");
}
client.Timeout = new TimeSpan(0, 5, 59);
client.BaseAddress = new Uri(baseAddress);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Add("Authorization", string.Format("Bearer {0}", _cred.eBayToken));
client.DefaultRequestHeaders.Add("Accept-Language", "en-US");
client.DefaultRequestHeaders.Add("Accept-Charset", "utf-8");
client.DefaultRequestHeaders.Add("Accept", "application/json");
client.DefaultRequestHeaders.Add("LegacyUse", "true");
return client;
}
public HttpResponseMessage PostHttpResponse(string requestUri, object data)
{
var stringPayload = JsonConvert.SerializeObject(data);
var httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/json");
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
httpContent.Headers.Add("Content-Language", "en-US");
httpContent.Headers.Add("Content-Encoding", "gzip");
using (var client = CreateHttpClient())
{
try
{
HttpResponseMessage response = client.PostAsJsonAsync(requestUri, httpContent).Result;
if (response.IsSuccessStatusCode)
{
return response;
}
else
{
GetErrorsResponse(response);
throw new HttpRequestException(string.Format("There was an exception trying to post a request. response: {0}", response.ReasonPhrase));
}
}
catch (HttpRequestException ex)
{
throw ex;
//return null;
}
}
}
Thank in advance for the help. It is very much appreciated.

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.

Restsharp SimpleAuthenticator

I'm using restsharp to make rest api client. This is my code:
var client = new RestClient("https://url.com");
client.Authenticator = new SimpleAuthenticator("client_id", "testapi", "client_secret", "password");
var request = new RestRequest("webapi/rest/auctions", Method.GET);
request.AddParameter("limit", "10");
request.AddParameter("order", "auction_id");
request.AddParameter("page", "1");
request.AddParameter("offset", "0");
IRestResponse response = client.Execute(request);
Console.WriteLine("request: " + response.Content);
Response is always: {"error":"unauthorized_client"}
And here is information from documentation of this rest api

Categories

Resources