What purposes should I use class StringContent for? - c#

There is StringContent class in System.Net.Http namespace. What purposes should I use class StringContent for?

StringContent class creates a formatted text appropriate for the http server/client communication. After a client request, a server will respond with a HttpResponseMessageand that response will need a content, that can be created with the StringContent class.
Example:
string csv = "content here";
var response = new HttpResponseMessage();
response.Content = new StringContent(csv, Encoding.UTF8, "text/csv");
response.Content.Headers.Add("Content-Disposition",
"attachment;
filename=yourname.csv");
return response;
In this example, the server will respond with the content present on the csv variable.

It provides HTTP content based on a string.
Example:
Adding the content on HTTPResponseMessage Object
response.Content = new StringContent("Place response text here");

Whenever I want to send an object to web api server I use StringContent to add format to HTTP content, for example to add Customer object as json to server:
public void AddCustomer(Customer customer)
{
String apiUrl = "Web api Address";
HttpClient _client= new HttpClient();
string JsonCustomer = JsonConvert.SerializeObject(customer);
StringContent content = new StringContent(JsonCustomer, Encoding.UTF8, "application/json");
var response = _client.PostAsync(apiUrl, content).Result;
}

Every response that is basically text encoded can be represented as StringContent.
Html reponse is text too (with proper content type set):
response.Content = new StringContent("<html><head>...</head><body>....</body></html>")
On the other side, if you download/upload file, that is binary content, so it cannot be represented by string.

Related

Unsupported media type in httpclient call c#

I'm a trying to post the following request but I am getting a "Unsupported Media Type" response. I am setting the Content-Type to application/json. Any help would be appreciated. And as per comment below, if i change content as 'new StringContent(JsonConvert.SerializeObject(root), Encoding.UTF8, "application/json")' then i get bad request response
string URL = "https://test.com/api/v2/orders/"; //please note it is dummy api endpoint
var client = new HttpClient();
var httpRequestMessage = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri(URL),
Headers = {
{ HttpRequestHeader.Authorization.ToString(), "Bearer ABcdwenlfbl8HY0aGO9Z2NacFj1234" }, //please note it is dummy bearer token
{ HttpRequestHeader.Accept.ToString(), "application/json;indent=2" },
{ HttpRequestHeader.ContentType.ToString(), "application/json" }
},
//Content =new StringContent(JsonConvert.SerializeObject(root), Encoding.UTF8, "application/json")
Content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(root))
};
var response = client.SendAsync(httpRequestMessage).Result;
With HttpClient, some headers are counted as request headers, and others are counted as content headers. I'm not sure why they made this distinction really, but the bottom line is that you have to add headers in the correct place.
In the case of Content-Type, this can be added as part of the StringContent constructor, or to the constructed StringContent object.
My approach is to use the constructor:
Content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(root), System.Text.Encoding.UTF8, "application/json");
Or alternatively set it afterwards:
Content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(root))
Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
Note: If your issue still presents after making this change, then it's likely a server-side problem and you'll need to contact the maintainer of the API to ask what you're doing wrong.
I prefer using some third party wrappers like FluentClient
Note that you should not instance a new object for every request, O only did it for the sake of an example.
var client = new FluentClient("https://test.com/api/v2/orders/")
.PostAsync(URI)
.WithBody(root)
.WithBearerAuthentication("ABcdwenlfbl8HY0aGO9Z2NacFj1234");
var response = await client.AsResponse();

Send http get with request body c#

I want to send an HTTP GET with a request body. I know there is much heated debate about whether this should ever be done or not but I am not interested in debating it I simply want to do it. I'm using C# and ASP.NET and my code is below. Unfortunately it throws an exception "Cannot send a content-body with this verb type". Please, any help on how to get this done will be very appreciated!
// Serialize our concrete class into a JSON String
var stringPayload = JsonConvert.SerializeObject(memRequest);
// Wrap our JSON inside a StringContent which then can be used by the HttpClient class
var httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/json");
using (var httpClient = new HttpClient())
{
HttpRequestMessage request = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = u,
Content = httpContent
};
var result = httpClient.SendAsync(request).Result;
result.EnsureSuccessStatusCode();
var responseBody = result.Content.ReadAsStringAsync().ConfigureAwait(false);

Xamarin Forms Post Request Body

public async static Task<RootUserData> getUSerLoggedIn(string userName, string password)
{
RootUserData rootUserData = new RootUserData();
var url = URlConstants.LOGIN_URL;
using (HttpClient httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes($"{userName}:{password}");
httpClient.DefaultRequestHeaders.Add("content-type", "application/json");
httpClient.DefaultRequestHeaders.Add("cache-control", "no-cache");
} ;
}
I am using above code to make one Service call. I have to pass userEmailAddress in body as plain as shown in Postman Picture. Can You Please help me How to achieve this?
No... Its in Plain Text
Set your content mime type to "text/plain":
httpClient.DefaultRequestHeaders.Add("content-type", "text/plain");
And post a string:
var response = await httpClient.PostAsync(url, new StringContent(userName));
Content-Type should not be added like that, It didn't work in my case, and gave a wrong response, instead
Pass content-Type like this -
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded");

RESTful API newbie question about error 400

The question is following:
I am having very simple POST method on the server side:
[HttpPost]
[Route("//api/loggeduser")]
public void Post([FromBody] LoggedUser loggedUser)
I am trying to call it from the client side:
var loggedUser = new LoggedUser
{
UserName = userName,
Logged = true
};
var json = JsonConvert.SerializeObject(loggedUser);
HttpClient _httpClient = new HttpClient();
HttpContent httpContent = new StringContent(json);
response = await _httpClient.PostAsync("https://localhost:44311/api/loggeduser", httpContent);
And I always getting error 400. What I am doing wrong? Any suggestions? Thanks in advance.
I think it might work if you tell the StringContent which encoding and content type it should use, like this:
HttpContent httpContent = new StringContent(json, Encoding.UTF8, "application/json");
You have an invalid syntax. Whatever information you're attempting to send it is not formatted in a way that the server is willing to accept. You need to check the parameters and make sure you have it written in the correct syntax.
You can try to let content-type to be application/json.
StringContent content = new StringContent(json, Encoding.UTF8, "application/json");

Unable to Send JSON data to HttpClient in C# Android

I'm trying to do something that seems like it should be simple: to send a JSON request to a PHP script on my webserver and get the response.
I can request the site without issue, I can read the response without issue, but for some reason this refuses to send the contents of my JSON data.
string url = "https://www.exampleserver.com/examplescript.php";
HttpClient client = new HttpClient(new Xamarin.Android.Net.AndroidClientHandler());
client.BaseAddress = new Uri(url);
string jsonData = #"{""key1"" : ""data1"",""key2"" : ""data2"",""key3"" : ""data3""}";
HttpContent content = new StringContent(jsonData, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(url, content);
string result = await response.Content.ReadAsStringAsync();
responsebox.Text = result;
Each time I run it the contents of responsebox.Text is replaced with the default contents of the page pointing out explicitly that there was no content in the $_POST data. (Even checked $_REQUEST to make sure it wasn't showing up as GET).
I know it's gotta be something simple, but I can't find it.

Categories

Resources