zoukankan      html  css  js  c++  java
  • HttpClient PostAsync/GetAsync JSON Example

    PostAsync

    static readonly HttpClient Client = new HttpClient();
    public async Task<T> PostAsync<T>(string url, object data) where T : class, new()
    {
        try
        {
            string content = JsonConvert.SerializeObject(data);
            var buffer = Encoding.UTF8.GetBytes(content);
            var byteContent = new ByteArrayContent(buffer);
            byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            var response = await Client.PostAsync(url, byteContent).ConfigureAwait(false);
            string result = await response.Content.ReadAsStringAsync();
            if (response.StatusCode != HttpStatusCode.OK)
            {
                logger.Error($"GetAsync End, url:{url}, HttpStatusCode:{response.StatusCode}, result:{result}");
                return new T();
            }
            logger.Info($"GetAsync End, url:{url}, result:{result}");
            return JsonConvert.DeserializeObject<T>(result);
        }
        catch (WebException ex)
        {
            if (ex.Response != null)
            {
                string responseContent = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
                throw new System.Exception($"response :{responseContent}", ex);
            }
            throw;
        }
    }
    

      

    GetAsync

    static readonly HttpClient Client = new HttpClient();
    public async Task<string> GetAsync(string url, object data)
    {
        try
        {
            string requestUrl = $"{url}?{GetQueryString(data)}";
            logger.Info($"GetAsync Start, requestUrl:{requestUrl}");
            var response = await Client.GetAsync(requestUrl).ConfigureAwait(false);
            string result = await response.Content.ReadAsStringAsync();
            logger.Info($"GetAsync End, requestUrl:{requestUrl}, HttpStatusCode:{response.StatusCode}, result:{result}");
            return result;
        }
        catch (WebException ex)
        {
            if (ex.Response != null)
            {
                string responseContent = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
                throw new Exception($"Response :{responseContent}", ex);
            }
            throw;
        }
    }
    
    private static string GetQueryString(object obj)
    {
        var properties = from p in obj.GetType().GetProperties()
                            where p.GetValue(obj, null) != null
                            select p.Name + "=" + HttpUtility.UrlEncode(p.GetValue(obj, null).ToString());
    
        return String.Join("&", properties.ToArray());
    }
    

      

  • 相关阅读:
    【转】ServletContext介绍及用法
    【转】UML之类图和对象图
    【转】UML各种图总结
    解决win10下 matplotlib绘图时中文乱码问题
    修改表、字段的默认字符集
    MySQL报错Incorrect date value: '0000-00-00' for column 'hirrdate' at row 1
    用vs code将qt designer的.ui文件转换为.py文件
    MySQL多表数据查询记录
    MySQL中统计函数和分组数据查询
    lambda匿名函数
  • 原文地址:https://www.cnblogs.com/XuPengLB/p/10860949.html
Copyright © 2011-2022 走看看