Send by value in Body with HttpClient class

Hi Guys, I'd like to know how can I send (post) data in body with bearer? I try to use HttpClient, but, I don't know how to load in body my informations. When I use Postman, I can send, but when I need to send it through C# I don't know how to send it. I try two ways:
var objAnonymous = new {
prop1 = "prop1",
prop2 = "prop2",
prop3 = "prop3",
prop4 = "prop4",
prop5 = "prop5"
};
var objString = JsonConvert.SerializeObject(objAnonymous);
var request = new HttpRequestMessage(HttpMethod.Post, "url");
request.Content = new StringContent(objString, Encoding.UTF8);
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
request.Headers.Authorization =
new AuthenticationHeaderValue("Bearer", token);
var response = await httpClient.SendAsync(request);
response.EnsureSuccessStatusCode();

var result = await response.Content.ReadAsStringAsync();
var objAnonymous = new {
prop1 = "prop1",
prop2 = "prop2",
prop3 = "prop3",
prop4 = "prop4",
prop5 = "prop5"
};
var objString = JsonConvert.SerializeObject(objAnonymous);
var request = new HttpRequestMessage(HttpMethod.Post, "url");
request.Content = new StringContent(objString, Encoding.UTF8);
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
request.Headers.Authorization =
new AuthenticationHeaderValue("Bearer", token);
var response = await httpClient.SendAsync(request);
response.EnsureSuccessStatusCode();

var result = await response.Content.ReadAsStringAsync();
and
HttpClient httpClient = new HttpClient();

var objAnonymous = new {
prop1 = "prop1",
prop2 = "prop2",
prop3 = "prop3",
prop4 = "prop4",
prop5 = "prop5"
};

var objString = JsonConvert.SerializeObject(objAnonymous);

httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", "token");
var content = new StringContent(objString, Encoding.UTF8, "application/json");
var response = await httpClient.PostAsync("url", content);
response.EnsureSuccessStatusCode();
var result = await response.Content.ReadAsStringAsync();
HttpClient httpClient = new HttpClient();

var objAnonymous = new {
prop1 = "prop1",
prop2 = "prop2",
prop3 = "prop3",
prop4 = "prop4",
prop5 = "prop5"
};

var objString = JsonConvert.SerializeObject(objAnonymous);

httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", "token");
var content = new StringContent(objString, Encoding.UTF8, "application/json");
var response = await httpClient.PostAsync("url", content);
response.EnsureSuccessStatusCode();
var result = await response.Content.ReadAsStringAsync();
2 Replies
undisputed world champions
in your code you use StringContent, but in postman you seem to be using form-data have you tried using FormUrlEncodedContent instead, maybe?
Ale Kantousian
Ale KantousianOP2y ago
I haven't tried with FormUrlEncodedContent yet It worked, thanks friend!
Want results from more Discord servers?
Add your server