How to call Rest API with Content and Headers in c#? - c#

I am trying to call Rest API with content and headers in c#. Actually I am trying to convert to c# from Python code which is:
import requests
url = 'http://url.../token'
payload = 'grant_type=password&username=username&password=password'
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
response = requests.request('POST', url, headers = headers, data = payload, allow_redirects=False)
print(response.text)
So far I am trying with:
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(Url);
var tmp = new HttpRequestMessage
{
Method = HttpMethod.Post,
Content =
{
}
};
var result = client.PostAsync(Url, tmp.Content).Result;
}
I have no idea how to put from Python code Headers (Content-Type) and additional string (payload).

If you use RestSharp, you should be able to call your service with the following code snipped
var client = new RestClient("http://url.../token");
var request = new RestRequest(Method.POST);
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddParameter("application/x-www-form-urlencoded", "grant_type=password&username=username&password=password", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
var result = response.Content;
I based my answer on the anwser of this answer.

Here a sample I use in one of my apps:
_client = new HttpClient { BaseAddress = new Uri(ConfigManager.Api.BaseUrl),
Timeout = new TimeSpan(0, 0, 0, 0, -1) };
_client.DefaultRequestHeaders.Accept.Clear();
_client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
_client.DefaultRequestHeaders.Add("Bearer", "some token goes here");

using System.Net.Http;
var content = new StringContent("grant_type=password&username=username&password=password");
content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
client.PostAsync(Url, content);
Or use FormUrlEncodedContent without set header
var data = new Dictionary<string, string>
{
{"grant_type", "password"},
{"username", "username"},
{"password", "password"}
};
var content = new FormUrlEncodedContent(data);
client.PostAsync(Url, content);
If you write UWP application, use HttpStringContent or HttpFormUrlEncodedContent instead in Windows.Web.Http.dll.
using Windows.Web.Http;
var content = new HttpStringContent("grant_type=password&username=username&password=password");
content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
client.PostAsync(Url, content);
var data = new Dictionary<string, string>
{
{"grant_type", "password"},
{"username", "username"},
{"password", "password"}
};
var content = new FormUrlEncodedContent(data);
client.PostAsync(Url, content);

Related

RestSharp to HttpClient

var client = new RestClient("http://10.0.0.244:8885/terminal/info");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("apikey", "adasdsadasd");
var body = #"{}";
request.AddParameter("application/json", body, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
Could someone, please, help me write this code with HttpClient?
I try following code.
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://10.0.0.244:8885/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Clear();
HttpRequestMessage request = new HttpRequestMessage();
request.Method = HttpMethod.Post;
request.RequestUri = new Uri($"{client.BaseAddress}/terminal/info");
request.Headers.Add("apikey", "adasdsadasd");
var body = Newtonsoft.Json.JsonConvert.SerializeObject(new { });
request.Content = new StringContent(body, Encoding.UTF8, "application/json");//CONTENT-TYPE header
request.Content.Headers.Clear();
request.Content.Headers.ContentLength = 2;
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.SendAsync(request).GetAwaiter().GetResult();
var x = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
}
But it response with Status Code 400 (ParseError)
You can accomplish what you are trying to do with much less code. Also this should be in an async method. Below is an example
internal async Task<string> GetResponse()
{
using var client = new HttpClient();
client.BaseAddress = new Uri("http://10.0.0.244:8885/");
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Add("apikey", "adasdsadasd");
var content = new StringContent("{}", Encoding.UTF8, "text/plain");
var response = await client.PostAsync("/terminal/info", content);
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsStringAsync();
}
return null;
}

ASP.NET Web API post to an external api

I would like to ask if it is possible for a created ASP.NET Web API (written in C#) to post to an external API?
If it is possible, please share sample code that can post to an url with adding headers and receive a callback from the external API.
A simple way to make HTTP-Request out of a .NET-Application is the System.Net.Http.HttpClient (MSDN). An example usage would look something like this:
// Should be a static readonly field/property, wich is only instanciated once
var client = new HttpClient();
var requestData = new Dictionary<string, string>
{
{ "field1", "Some data of the field" },
{ "field2", "Even more data" }
};
var request = new HttpRequestMessage() {
RequestUri = new Uri("https://domain.top/route"),
Method = HttpMethod.Post,
Content = new FormUrlEncodedContent(requestData)
};
request.Headers // Add or modify headers
var response = await client.SendAsync(request);
// To read the response as string
var responseString = await response.Content.ReadAsStringAsync();
// To read the response as json
var responseJson = await response.Content.ReadAsAsync<ResponseObject>();
Essentially you need use an instance of HttpClient to send an HttpRequestMessage to an endpoint.
Here is an example to post some jsonData to someEndPointUrl:
var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, someEndPointUrl);
request.Headers.Accept.Clear();
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
request.Content = new StringContent(jsonData, Encoding.UTF8, "application/json");
var response = await client.SendAsync(request, CancellationToken.None);
var str = await response.Content.ReadAsStringAsync();
if (response.StatusCode == HttpStatusCode.OK)
{
// handle your response
}
else
{
// or failed response ?
}

How can I Post parameter in httpClient where in postman use param

I want to post my parameter with HttpClient .
what is the Content in httpclient request body? I wrote it int the body part and when I run the project I get Error.
my code is:
string baseAddress = "https://WebServiceAddress";
Client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
HttpRequestMessage bodyRequest = new HttpRequestMessage(HttpMethod.Post, baseAddress)
bodyRequest.Content = new StringContent(JsonConvert.SerializeObject(Prescriptionrequest), Encoding.UTF8, "application/json");
var responseApi = Client.PostAsync(baseAddress, bodyRequest.Content, new System.Threading.CancellationToken(false));
what should be the format of bodyRequest.Content?
Use this code:
HttpClient client = new HttpClient();
var dictionary = new Dictionary<string, string>
{
{ "parameter0", "value0" },
{ "parameter1", "value1" }
};
var content = new FormUrlEncodedContent(dictionary);
var response = await client.PostAsync("https://WebServiceAddress", content);
var responseString = await response.Content.ReadAsStringAsync();

C# - Body content in POST request

I need to make some api calls in C#. I'm using Web API Client from Microsoft to do that. I success to make some POST requests, but I don't know how to add the field "Body" into my requests. Any idea ?
Here's my code:
static HttpClient client = new HttpClient();
public override void AwakeFromNib()
{
base.AwakeFromNib();
notif_button.Activated += (sender, e) => {
};
tips_button.Activated += (sender, e) =>
{
Tip t1 = new Tip(title_tips.StringValue, pic_tips.StringValue, content_tips.StringValue, "TEST");
client.BaseAddress = new Uri("my_url");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
CreateProductAsync(t1).Wait();
};
}
static async Task<Uri> CreateProductAsync(Tip tips)
{
HttpResponseMessage response = await client.PostAsJsonAsync("api/add_tips", tips);
response.EnsureSuccessStatusCode();
return response.Headers.Location;
}
Step 1. Choose a type that derives from HttpContent. If you want to write a lot of content with runtime code, you could use a StreamContent and open some sort of StreamWriter on it. For something short, use StringContent. You can also derive your own class for custom content.
Step 2. Pass the content in a call to HttpClient.PostAsync.
Here's an example that uses StringContent to pass some JSON:
string json = JsonConvert.SerializeObject(someObject);
var httpContent = new StringContent(json, Encoding.UTF8, "application/json");
var httpResponse = await httpClient.PostAsync("http://www.foo.bar", httpContent);
See also How do I set up HttpContent?.
Thanks to this and this, I finally found the solution to send post requests with headers AND body content. Here's the code:
var cl = new HttpClient();
cl.BaseAddress = new Uri("< YOUR URL >");
int _TimeoutSec = 90;
cl.Timeout = new TimeSpan(0, 0, _TimeoutSec);
string _ContentType = "application/x-www-form-urlencoded";
cl.DefaultRequestHeaders.Add(key, value);
cl.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(_ContentType));
cl.DefaultRequestHeaders.Add("key", "value");
cl.DefaultRequestHeaders.Add("key", "value");
var _UserAgent = "d-fens HttpClient";
cl.DefaultRequestHeaders.Add("User-Agent", _UserAgent);
var nvc = new List<KeyValuePair<string, string>>();
nvc.Add(new KeyValuePair<string, string>("key of content", "value"));
var req = new HttpRequestMessage(HttpMethod.Post, "http://www.t-lab.fr:3000/add_tips") { Content = new FormUrlEncodedContent(nvc) };
var res = cl.SendAsync(req);
a little more understandable
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
client.DefaultRequestHeaders.Add("Accept", "*/*");
var Parameters = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("Id", "1"),
};
var Request = new HttpRequestMessage(HttpMethod.Post, "Post_Url")
{
Content = new FormUrlEncodedContent(Parameters)
};
var Result = client.SendAsync(Request).Result.Content.ReadAsStringAsync();
}

Trustpilot OAuth Restful API: Unable to PostAsync

I am trying to use the Trustpilot API, to post invitations to review products.
I have successfully gone through the authentication step as you can see in the code below, however I am unable to successfully post data to the Trustpilot Invitations API. The PostAsnyc method appears to be stuck with an WaitingForActivation status. I wonder if there is anything you can suggest to help.
Here is my code for this (the API credentials here aren't genuine!):
using (HttpClient httpClient = new HttpClient())
{
string trustPilotAccessTokenUrl = "https://api.trustpilot.com/v1/oauth/oauth-business-users-for-applications/accesstoken";
httpClient.BaseAddress = new Uri(trustPilotAccessTokenUrl);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
var authString = "MyApiKey:MyApiSecret";
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Base64Encode(authString));
var stringPayload = "grant_type=password&username=MyUserEmail&password=MyPassword";
var httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/x-www-form-urlencoded");
HttpResponseMessage httpResponseMessage = httpClient.PostAsync(trustPilotAccessTokenUrl, httpContent).Result;
var accessTokenResponseString = httpResponseMessage.Content.ReadAsStringAsync().Result;
var accessTokenResponseObject = JsonConvert.DeserializeObject<AccessTokenResponse>(accessTokenResponseString);
// Create invitation object
var invitation = new ReviewInvitation
{
ReferenceID = "inv001",
RecipientName = "Jon Doe",
RecipientEmail = "Jon.Doe#comp.com",
Locale = "en-US"
};
var jsonInvitation = JsonConvert.SerializeObject(invitation);
var client = new HttpClient();
client.DefaultRequestHeaders.Add("token", accessTokenResponseObject.AccessToken);
var invitationsUri = new Uri("https://invitations-api.trustpilot.com/v1/private/business-units/{MyBusinessID}/invitations");
// This here as a status of WaitingForActivation!
var a = client.PostAsync(invitationsUri, new StringContent(jsonInvitation)).ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode());
}
This is how I solved the issue:
// Serialize our concrete class into a JSON String
var jsonInvitation = JsonConvert.SerializeObject(invitationObject);
// Wrap our JSON inside a StringContent which then can be used by the HttpClient class
var stringContent = new StringContent(jsonInvitation);
// Get the access token
var token = GetAccessToken().AccessToken;
// Create a Uri
var postUri = new Uri("https://invitations-api.trustpilot.com/v1/private/business-units/{BusinessUnitID}/invitations");
// Set up the request
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, postUri);
request.Content = stringContent;
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
request.Content.Headers.Add("token", token);
// Set up the HttpClient
var httpClient = new HttpClient();
//httpClient.DefaultRequestHeaders.Accept.Clear();
//httpClient.BaseAddress = postUri;
//httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
//httpClient.DefaultRequestHeaders.AcceptLanguage.Add(new StringWithQualityHeaderValue("en-US"));
var task = httpClient.SendAsync(request);
task.Wait();
This question here on SO was helpful:
How do you set the Content-Type header for an HttpClient request?

Categories

Resources