Httpclient Post With Parameters in Body

HttpClient post with parameters in body

My understanding is that for UWP apps Windows.Web.Http.HttpClient() is the recommended way to do this, plus make sure your URL's do not have typos. :)

         var url = AppConstants.ApiLoginUrl;
var uriRequest = new Uri(url);

var content = new HttpFormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("username", email),
new KeyValuePair<string, string>("password", password)
});

using (var httpClient = new Windows.Web.Http.HttpClient())
{
try
{
var httpResponse = await httpClient.PostAsync(uriRequest, content);

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

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

HttpClient POST with HttpParams

The 2nd parameter of post is the http body that you want to send in the request. If there is no body then pass null for the argument. Then pass the params as the 3rd argument of the call.

  .post<ServiceResponse>(url, null, { params: params })

The reason that get has a different method signature is that you can't pass a http body with a http get call.

Add Params HttpClient C#

When you format your URL you need to add the parameters like so:

var url = string.Format("{0}{1}", ServicePrefix, controller);

url = string.Format("{0}?token=123456", url);

Note the ? between the URL and the query parameter.

You don't specify how you get the value for token into your method but, if it is a readonly value similar to ServicePrefix you can pass it as a parameter to string.Format:

var url = string.Format("{0}{1}", ServicePrefix, controller);

url = string.Format("{0}?token={1}", url, Token);

You can always put this on one line, but I have split it to make it easier to read :-)

Httpclient POST with Parameters

The method you are using takes everything in the 2nd parameter and uses it for HttpContent. You can read more here. What you should be doing is appending the parameters to myUri variable.

C# HttpClient: How to send query strings in POST Requests

Apparently, None of the tried approaches put parameters in the URL!. You are posting on the below URL

"http://mywebsite.com/api/CompleteService"

However, something that works

string url = "http://mywebsite.com/api/CompleteService?";
string refId = "12345";
string price= "600";
string param = $"refId={refId}&productPrice={price}";
HttpContent content = new StringContent(param, Encoding.UTF8, "application/json");

Attach Parameters to URL and to get Response's Body, Use:

  try   
{
HttpResponseMessage response = await client.PostAsync(url + param, content);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch(HttpRequestException e)
{
Console.WriteLine("Message :{0} ",e.Message);
}

C#: HttpClient with POST parameters

A cleaner alternative would be to use a Dictionary to handle parameters. They are key-value pairs after all.

private static readonly HttpClient httpclient;

static MyClassName()
{
// HttpClient is intended to be instantiated once and re-used throughout the life of an application.
// Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads.
// This will result in SocketException errors.
// https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=netframework-4.7.1
httpclient = new HttpClient();
}

var url = "http://myserver/method";
var parameters = new Dictionary<string, string> { { "param1", "1" }, { "param2", "2" } };
var encodedContent = new FormUrlEncodedContent (parameters);

var response = await httpclient.PostAsync (url, encodedContent).ConfigureAwait (false);
if (response.StatusCode == HttpStatusCode.OK) {
// Do something with response. Example get content:
// var responseContent = await response.Content.ReadAsStringAsync ().ConfigureAwait (false);
}

Also dont forget to Dispose() httpclient, if you dont use the keyword using

As stated in the Remarks section of the HttpClient class in the Microsoft docs, HttpClient should be instantiated once and re-used.

Edit:

You may want to look into response.EnsureSuccessStatusCode(); instead of if (response.StatusCode == HttpStatusCode.OK).

You may want to keep your httpclient and dont Dispose() it. See: Do HttpClient and HttpClientHandler have to be disposed?

Edit:

Do not worry about using .ConfigureAwait(false) in .NET Core. For more details look at https://blog.stephencleary.com/2017/03/aspnetcore-synchronization-context.html



Related Topics



Leave a reply



Submit