Reputation: 279
Currently I am working with HttpClient
, but I am unable to understand which parameter I have to pass, i.e. string content or bytes content.
Code 1:
ModelAttribute modelAttribute = new ModelAttribute {Id=modelId, Type="new", MakeId = makeId};
RefreshWrapper refreshWrapper = new RefreshWrapper(){ ModelAttribute = new List<ModelAttribute>{modelAttribute}};
var jsonInString = JsonConvert.SerializeObject(refreshWrapper);
string baseUrl = string.Format("http://localhost:8090/api/abc");
var buffer = System.Text.Encoding.UTF8.GetBytes(jsonInString);
var byteContent = new ByteArrayContent(buffer);
byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
HttpClient client = new HttpClient();
client.BaseAddress = new System.Uri(baseUrl);
var result=client.PostAsync("", byteContent).Result;
Code 2:
ModelAttribute modelAttribute = new ModelAttribute {Id=modelId, Type="new", MakeId = makeId};
RefreshWrapper refreshWrapper = new RefreshWrapper(){ ModelAttribute = new List<ModelAttribute>{modelAttribute}};
var jsonInString = JsonConvert.SerializeObject(refreshWrapper);
string baseUrl = string.Format("http://localhost:8090/apabci/");
HttpClient client = new HttpClient();
client.PostAsync(baseUrl, new StringContent(jsonInString, Encoding.UTF8, "application/json"));
Which one is better?
Upvotes: 1
Views: 6569
Reputation: 262
I always use methods that look like this:
using System.Net.Http;
HttpClient client = new HttpClient();
public async Task<List<Object>> GetObjectAsync()
{
try
{
string url = "http://yourapiurl.com/";
var response = await client.GetStringAsync(url);
var objectsReturned = JsonConvert.DeserializeObject<List<Object>>(response);
return objectsReturned;
}
catch (Exception ex)
{
throw ex;
}
}
public async Task AddObjectAsync(Object object)
{
try
{
string url = "http://yourapiurl.com/{0}";
var uri = new Uri(string.Format(url, object.Id));
var data = JsonConvert.SerializeObject(object);
var content = new StringContent(data, Encoding.UTF8, "application/json");
HttpResponseMessage response = null;
response = await client.PostAsync(uri, content);
if (!response.IsSuccessStatusCode)
{
throw new Exception("Error");
}
}
catch(Exception ex)
{
throw ex;
}
}
In the PostAsync Method, I send an Serialized Object to the API, {0} is the parameter that will be exchanged for the serialized object.
Upvotes: 1