WPF | 实现一个可重用的工具类 UseFetch

1 概述

UseFetch工具类可以获取数据,并能够序列化和反序列化对象。

2 代码实现

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;

public static class UseFetch
    {
    
    
        public static TResponse Get<TResponse>(string url,
            Dictionary<string, string> headers = null)
            where TResponse : class
        {
    
    
            try
            {
    
    
                var client = new HttpClient();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                if (headers != null)
                {
    
    
                    foreach (var header in headers)
                    {
    
    
                        client.DefaultRequestHeaders.Add(header.Key, header.Value);
                    }
                }

                var response = client.GetAsync(url).Result;

                var responseString = response.Content.ReadAsStringAsync().Result;

                var deserializedResponse = JsonConvert.DeserializeObject<TResponse>(responseString);

                return deserializedResponse;
            }
            catch (Exception e)
            {
    
    
                throw new Exception(e.ToString());
            }
        }

        public static TResponse Post<TResponse, TRequest>(string url, TRequest request,
            Dictionary<string, string> headers = null)
            where TRequest : class, new()
            where TResponse : class
        {
    
    
            try
            {
    
    
                var serializeRequest = JsonConvert.SerializeObject(request);

                var content = new StringContent(serializeRequest);
                content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

                var client = new HttpClient();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                if (headers != null)
                {
    
    
                    foreach (var header in headers)
                    {
    
    
                        client.DefaultRequestHeaders.Add(header.Key, header.Value);
                    }
                }

                var response = client.PostAsync(url, content).Result;

                var responseString = response.Content.ReadAsStringAsync().Result;

                var deserializedResponse = JsonConvert.DeserializeObject<TResponse>(responseString);

                return deserializedResponse;
            }
            catch (Exception e)
            {
    
    
                throw new Exception(e.ToString());
            }
        }
    }

猜你喜欢

转载自blog.csdn.net/alexwei2009/article/details/125341886
今日推荐