Posting Jsonobject With Httpclient from Web API

POSTing JsonObject With HttpClient From Web API

With the new version of HttpClient and without the WebApi package it would be:

var content = new StringContent(jsonObject.ToString(), Encoding.UTF8, "application/json");
var result = client.PostAsync(url, content).Result;

Or if you want it async:

var result = await client.PostAsync(url, content);

Send a json on a post request with HttpClient and C#

It looks like you want to post a json in the request. Try to define the right content-type that is application/json. For sample:

request.Content = new StringContent("{\"priority\" : \"High\"}",
Encoding.UTF8,
"application/json");

Since your method returns a string it can be a a non-async method. The method SendAsync is async and you have to wait the request finished. You could try to call Result after the request. For sample:

var response =  httpClient.SendAsync(request).Result;
return response.Content; // string content

And you will get an object of HttpResponseMessage. There are a lot of useful information about the response on it.

preparing Json Object for HttpClient Post method

You need to either manually serialize the object first using JsonConvert.SerializeObject

var values = new Dictionary<string, string> 
{
{"type", "a"}, {"card", "2"}
};
var json = JsonConvert.SerializeObject(values);
var data = new StringContent(json, Encoding.UTF8, "application/json");

//...code removed for brevity

Or depending on your platform, use the PostAsJsonAsync extension method on HttpClient.

var values = new Dictionary<string, string> 
{
{"type", "a"}, {"card", "2"}
};
var client = new HttpClient();
using(var response = client.PostAsJsonAsync(myUrl, values).Result) {
result = response.Content.ReadAsStringAsync().Result;
}

C# HttpClient Post using Json Object is failing

The best approach is to use an actual object and let NewtonsoftJson take care of the serialization.

You will need two nuget packages for this:

  1. Microsoft.AspNet.WebApi.Client
  2. Newtonsoft.Json

The code looks like this:

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace Custom.ApiClient
{
internal static class WebApiManager
{
//private const string _requestHeaderBearer = "Bearer";
private const string _responseFormat = "application/json";

private static readonly HttpClient _client;

static WebApiManager()
{

// Setup the client.
_client = new HttpClient { BaseAddress = new Uri("api url goes here"), Timeout = new TimeSpan(0, 0, 0, 0, -1) };

_client.DefaultRequestHeaders.Accept.Clear();
_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(_responseFormat));

// Add the API Bearer token identifier for this application.
//_client.DefaultRequestHeaders.Add(RequestHeaderBearer, ConfigHelper.ApiBearerToken);
}
public static async Task<T> Post<T>(object requestObject)
{//the request object is the object being sent as instance of a class
var response = _client.PostAsJsonAsync("api extra path and query params go here", requestObject);

return await ProcessResponse<T>(response);
}
private static async Task<T> ProcessResponse<T>(Task<HttpResponseMessage> responseTask)
{//T represents the respose you expect from this call
var httpResponse = await responseTask;

if(!httpResponse.IsSuccessStatusCode)
throw new HttpRequestException(httpResponse.ToString());

var dataResult = await httpResponse.Content.ReadAsAsync<T>();

return dataResult;
}
}
}

To use this code you need to do something like this:

var myObject = new Object_I_Want_To_Send();
//set some properties here

var response = await WebApiManager.Post<MyResponse>(myObject);

Sending json with .NET HttpClient to a WebAPI server

Since you are trying to POST json, you can add a reference to System.Net.Http.Formatting and post "Data" directly without having to serialize it and create a StringContent.

public async Task<HttpStatusCode> SendAsync(Data data)
{
HttpResponseMessage response = await _httpClient.PostAsJsonAsync(_url, content);

return response.StatusCode;
}

On your receiving side, you can receive the "Data" type directly.

 [HttpPost]
[ActionName("postdata")]
public async Task<HttpResponseMessage> PostData(Data jsonParam)
{

}

More info on these HttpClientExtensions methods can be found here - http://msdn.microsoft.com/en-us/library/hh944521(v=vs.118).aspx

Posting a dictionary as data to HTTPS server in C# using HTTPClient

Try using this approach, it works with the server I am sending data to.

var content = new StringContent("{some:json}");
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

client.DefaultRequestHeaders.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json;"));

HttpResponseMessage response = await client.PostAsync("https://SERVER_ADRESS", content);

I suspect the request header is the reason, and send StringContent instead of FormUrlEncodedContent



Related Topics



Leave a reply



Submit