简体   繁体   中英

HttpClient PostAsync parameters

Currently I am working with HttpClient , but I am unable to understand which parameter I have to pass, ie 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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM