HttpClient PostAsync参数

时间:2018-08-23 16:52:33

标签: c# httpclient

当前我正在使用HttpClient,但是我无法理解我必须传递哪个参数,即字符串内容或字节内容。

代码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;

代码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"));

哪个更好?

1 个答案:

答案 0 :(得分:1)

我总是使用如下所示的方法:

    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;
        }
    }

在PostAsync方法中,我向API发送了序列化对象,{0}是将与序列化对象交换的参数。