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

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

Related

RestSharp Post Json Object

I am trying to Post a simple Json object using RestSharp to add a new product. I'm getting an error response from the server
"{"status":400,"error":"There was a problem in the JSON you submitted: unexpected character (after ) at line 1, column 2 [parse.c:724] in '{'product':{'name':'Product name','opt1':'Colour'}}"}"
My code:
////
var json = "{\'product\':{\'name\':\'Product name\',\'opt1\':\'Colour\'}}";
IRestClient restClient = new RestClient();
IRestRequest request = new RestRequest()
{
Resource = "https://api.targetsite.com/products/"
};
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Accept", "application/xml");
request.AddHeader("authorization", "Bearer " + token);
request.RequestFormat = DataFormat.Json;
request.AddJsonBody(json);
IRestResponse response = restClient.Post(request);
////
I managed to achive the result I wanted using a curl statment but I would like to do it using RestSharp.
Curl statment -
curl -X POST -H "Content-type: application/json" -H "Authorization: Bearer <ACCESS_TOKEN>"
https://api.targetsite.com/products/ -d '{"product":{"name":"Product name","opt1":"Colour"}}'
This HttpClient call also works fine
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api.targetsite.com/products/"))
{
request.Headers.TryAddWithoutValidation("Authorization", "Bearer <ACCESS_TOKEN>");
request.Content = new StringContent("{\"product\":{\"name\":\"Product name\",\"opt1\":\"Colour\"}}");
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
var response = await httpClient.SendAsync(request);
}
}
It looks like a limitation on the API you are calling.
When you send the json with curl, you're using different delimiters (" instead of ').
My guess is that the API you're calling doesn't properly deserialize the JSON when ' is used.
What you can try is replacing the escaped ' with " or replace this line in your code : request.AddJsonBody(json)
with
request.AddJsonBody(Newtonsoft.Json.JsonConvert.DeserializeObject(json)) provided that you have installed the newtonsoft package.

Upload image from mobile app to API with multipart/form-data

I have this API where I receive an image to save it in a storage server. I've been testing the functionality in postman and works perfectly fine. But when it comes to the mobile app it does not send the image.
here you can see the Postman POST request
the code for the xamarin app is the next
var content = new MultipartFormDataContent();
var stream = File.OpenRead(_mediaFile.Path);
var streamcontent = new StreamContent(stream);
content.Add(streamcontent, "picture");
var client = new HttpClient();
HttpResponseMessage response = await cliente.PostAsync($"http://localhost:200/api/.../picture", content);
string result = response.Content.ReadAsStringAsync().Result;
Response responseData = JsonConvert.DeserializeObject<Response>(result);
if (response.IsSuccessStatusCode)
{
await Application.Current.MainPage.DisplayAlert("Correcto", "Imagen subida Correctamentel!", "OK");
_mediaFile = null;
terminado.IsEnabled = true;
}
else
{
terminado.IsEnabled = true;
await Application.Current.MainPage.DisplayAlert("Error", "Opps algo ocuirrio mal!", "OK"); }
As you can see in the postman the key picture receives the image name. I tried it also with curl and it works:
curl -X POST "http://localhost:200/api/.../picture" -H "accept: application/json" -H "Content-Type: multipart/form-data" -F "picture=#version1.jpeg;type=image/jpeg"
I've managed it to work, but using RestSharp library instead of HttpClient:
var client = new RestClient("192.168.0.2"); //the ip of your REST API
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "multipart/form-data"); // I'm using multipart form data
request.AddHeader("Authorization", "Bearer eyJ0eXAiOiJKV1QiLC"); // using JWT for auth
request.AddFile("pictureField", "/path/to/file"); //the path depends on which device you're using
IRestResponse response = client.Execute(request);
Pretty much straigt forward and works perfectly fine. Also, the "pictureField" depends on the name of the field the API requires, and the path to file should not be hardcoded. It should be given depending on where in the device the choosen image is.

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.

C# GitHub SCIM API // Difference between cURL and HttpClient

I'm facing a strange error with the usage of the GITHUB API.
When I contact them with cURL it's like:
curl.exe -H "Accept: application/vnd.github.cloud-9-preview+json+scim" -H "Authorization: Bearer TOKEN" https://api.github.com/scim/v2/organizations/[ORG]/Users
When I try to take it to C#, if became:
using (var cl = new HttpClient())
{
cl.DefaultRequestHeaders.Add("Accept", "application/vnd.github.cloud-9-preview+json+scim");
cl.DefaultRequestHeaders.Add("Authorization", "Bearer " + "TOKEN");
var val = cl.GetStringAsync("https://api.github.com/scim/v2/organizations/[ORG]/Users").Result;
}
When I run my cURL everything works fine but when I try the same on C# I got a 403 Error.
Could it be related to the "Accept" non standard field?
I find out that the GITHUB API requires to have the User-Agent header Set.
Setting it as "curl" made it.
using (var cl = new HttpClient())
{
cl.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/vnd.github.cloud-9-preview+json+scim"));
cl.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "token");
cl.DefaultRequestHeaders.UserAgent.Add(new System.Net.Http.Headers.ProductInfoHeaderValue("curl", "7.46.0"));
var val = cl.GetStringAsync("https://api.github.com/scim/v2/organizations/[ORG]/Users").Result;
}

Categories

Resources