How to convert a curl call to C# using HttpClient - c#

How do you convert a curl to be used in C# using HttpClient?
Here is the curl call that I need to use:
Request:
curl -i \
-X POST \
-H "X-Version: 1" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer Your Authorization Token" \
-H "Accept: application/json" \
-d '{"text":"Test Message","to":["Recipients Mobile Number"]}' \
-s \
https://api.clickatell.com/rest/message
I have basic knowledge of HttpClient and I know nothing of curl calls so this is what I could figure from Googling. Below is my code, not sure if it is correct?
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "abcdefghij0123456789");
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
httpClient.DefaultRequestHeaders.Add("X-Version", "1");
StringContent stringContent = new StringContent("{\"text\":\"Test Message\",\"to\":[\"27936906909\"]}");
stringContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
HttpResponseMessage httpResponseMessage = await httpClient.PostAsync("https://api.clickatell.com/rest/message", stringContent);
if (httpResponseMessage.IsSuccessStatusCode)
{
}
else
{
string failureMsg = "HTTP Status: " + httpResponseMessage.StatusCode.ToString() + " - Reason: " + httpResponseMessage.ReasonPhrase;
}
//string sjson = await httpResponseMessage.Content.ReadAsAsync<string>();
//return sjson;
}
Everything looks correct to be but when I run it then I keep on getting a bad request. I'm not sure how to fix this? Not sure if I missed something from the curl call?

I'll reply the same thing I always reply when someone is trying to debug network issues. Install wireshark, create a session with the traffic you want to mimic, then create another one with your own code. This will allow you to see exactly what is going on and which header are not transmitted correct.

Related

geeting HTTP Post BAD request converting CURL code to C# HTTP POST

Can someone please assist need to do post to url working fine on curl but not throufh C# HTTPPOST..
Here Curl code :
curl -H "Authorization: Basic ZWRpdG9yOnhYTXEgM09QNyB4WjlkIHpET3IgOVNhTiB1S3lx=="-H "description: {"path":"/shows/sheriffs-el-dorado-county/2020-2021-season/formats/","title":"HD-SEIN860","date":"2021-02-08","description":"STRIP / HD-SEIN860 / Airdate 02-10-2021"}" -X POST --data-binary #"C:/Users/sahithi.illindala/Downloads/HD-OZMR13091.pdf" http://ersyndication.wpengine.com/library/wp-json/wp/v2/media
Here is C# HTTPClient pOSt
using (var req = new HttpRequestMessage(new HttpMethod("POST"), "http://ersyndication.wpengine.com/library/wp-json/wp/v2/media"))
{
req.Headers.TryAddWithoutValidation("Authorization", "Basic ZWRpdG9yOnhYTXEgM09QNyB4WjlkIHpET3IgOVNhTiB1S3lx==");
//hc.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("attachment; filename = HD - SEIN860.pdf"));
req.Headers.TryAddWithoutValidation("Content-Disposition", "attachment; filename=HD-SEIN860.pdf");
req.Headers.TryAddWithoutValidation("description", "{\"path\":\"/shows/sheriffs-el-dorado-county/2020-2021-season/formats/\",\"title\":\"HD-SEIN860\",\"date\":\"2021-02-08\",\"description\":\"SI1234 / HD-SEIN860 / Airdate 02-10-2021\"}");
req.Content = new StringContent(File.ReadAllText("path"));
req.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded");
var response = await httpClient.SendAsync(req).ConfigureAwait(false);
var JsonResults = await response.Content.ReadAsStringAsync();

Using CURL to call WebRequest

Good day,
Been trying to call an API using CURL. The CURL is below. How can i pass the {BVN} inside?
curl --location --request GET 'https://api.paystack.co/bank/resolve_bvn/{BVN}' \
--header 'Authorization: Bearer SECRET_KEY'
The conversion of the CURL is as given below but i have issues passing the BVN parameter inside.
using (var httpClient = new HttpClient())
{ using (var request = new HttpRequestMessage(new HttpMethod("GET"),
"https://api.paystack.co/bank/resolve_bvn/{BVN}"))
{
request.Headers.TryAddWithoutValidation("Authorization", "Bearer SECRET_KEY");
var response = await httpClient.SendAsync(request);
}
}
I am not sure where the input is coming from, but you can do
string.format ("https://api.paystack.co/bank/resolve_bvn/{0}", BVN);
and the code for the string BVN will go into {0}

C# Windows Form HttpClient cURL

I need an example of sending a POST request to the server and getting a JSON response.
Problem in sending image.
I have a curl:
curl -k -v -X POST
-H "X-Auth-Token: 123"
-H "Content-Type: image / jpeg"
--data-binary # Face_foto.jpg http: // IP: port / 1 / storage / descriptors? estimate_attributes = 1.
How to implement it in C #
This should work:
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("X-Auth-Token", "123");
using (var stream = File.OpenRead(#"c:\somepath\somefile.jpg"))
{
using (var content = new StreamContent(stream))
{
content.Headers.Add("Content-Type", "image/jpeg");
var result = client.PostAsync("https://www.someuri.com", content).Result;
}
}
I wrote this in a hurry so watch out for issues with PostAsync and the File.OpenRead method.

cURL request in .NET to hide a comment in Facebook page

I read in this answer: facebook api hide comment that you can hide a Facebook comment using this cURL request:
curl -XPOST \
-k \
-F 'is_hidden=true' \
-F 'access_token=[access_token]' \
https://graph.facebook.com/v2.4/[comment_id]
How can I make that request in C#?
Please give a clear working code.
I think the -F flag means it is part of a multipart form: https://ec.haxx.se/http-multipart.html
This may not necessarily work but it should give an idea:
using (var client = new HttpClient())
{
using (var content =
new MultipartFormDataContent("upload----" + DateTime.Now.ToString(CultureInfo.InvariantCulture)))
{
content.Add(new StringContent("true"), "is_hidden");
content.Add(new StringContent("[access_token]"), "access_token");
var response = client.PostAsync(new Uri("https://graph.facebook.com/v2.4/[comment_id]"),
content).Result; // You could use await here
}
}

Connecting to a SOAP WSDL in Visual Studio C#

I am trying to connet my C# console application with a thridparty SOAP WSDL API however I cannot get it working.
I connect to the service with the WSDL string as a Service recourse in Visual studio: https://domain.tld/SimpleAPI/SimpleAPIService.svc?singleWsdl
The documentation says:
Authentication is sessions based. The requester must provide a valid session token in the Authenticate field of each request. A session has access to the same resources and capabilities as the given user. To get a session token, use the GetSessionToken method. To validate a session, use the PingPong method.
The documentation focuses on the REST API, which is not an option for me. The two methods for connecting is as follows:
curl \ -H "Content-Type: application/json" \ -X POST -d '{ "username": "admin#domain.com", "password": "VerySecure123" }' \ https://domain.tld/SimpleAPI/SimpleAPIService.svc/rest/GetSessionToken
This should return something like this: C9C5MlqrpMwG/6bQ3mAVlm0Z6hi/eh1vsQs4i1I/g==
This part is okay, I get a token back. However when I try the PingPong method, I get an error saying that it is a wrong token or the session has expired.
curl \ -H "Content-Type: application/json" \ -H "Authenticate:CCPSessionId C9C5MlqrpMwG/6bQ3mAVlm0Z6hi/eh1vsQs4i1I/g==" \ -X POST -d '{}' \ https://domain.tld/SimpleAPI/SimpleAPIService.svc/rest/PingPong
My code is as follows:
static void Main(string[] args)
{
string apiUsername = "user";
string apiPassword = "pass";
using (var client = new acmp.SimpleAPIServiceClient())
{
client.ClientCredentials.UserName.UserName = apiUsername;
client.ClientCredentials.UserName.Password = apiPassword;
string token = client.GetSessionToken(apiUsername, apiPassword);
string tokenText = string.Format("CCPSessionId {0}", token);
using (OperationContextScope contextScope = new OperationContextScope(client.InnerChannel))
{
var httpRequestProperty = new HttpRequestMessageProperty();
httpRequestProperty.Headers[HttpRequestHeader.Authorization] = token; //tokenText
OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;
client.PingPong();
}
}
Console.WriteLine("End...");
Console.ReadLine();
}
The theory right now is that my script is not passing the correct header.
Please help, we have spend so much time debugging.
Did a little reading up, and I can't find a token text of "CCPSessionsid " anywhere.
I see "bearer", token.AccessToken
Along the lines of:
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", token.AccessToken);
I also came across this issue while working with the same API. Cutting the quotation marks off the string solved this for me.
request.Headers.TryAddWithoutValidation("Authenticate", token.Trim(new Char[] {'"'}));

Categories

Resources