Http Client请求

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace demo.ApiClient
{
    public class WebApiClient
    {
        private readonly string _host;
        private readonly string _authToken;

        public WebApiClient(string host)
        {
            this._host = host;
        }
        public WebApiClient(string host, string token)
        {
            this._host = host;
            this._authToken = token;
        }

        public void Get<T>(string api, Action<T> callback)
        {
            using (var httpClient = NewClient())
            {
                var response=httpClient.GetAsync(FullAddressApi(api)).Result;
                callback(JsonConvert.DeserializeObject<T>(response.Content.ReadAsStringAsync().Result));
            }
        }
        private HttpClient NewClient()
        {
            var handler = new HttpClientHandler { AutomaticDecompression=DecompressionMethods.GZip };
            var client = new HttpClient(handler);
            if(!string.IsNullOrEmpty(_authToken))
                client.DefaultRequestHeaders.Authorization=new System.Net.Http.Headers.AuthenticationHeaderValue("Basic",_authToken);
            return client;
        }

        //POST提交
        public void Post<T, P>(string api, P data, Action<T> callback)
        {
            using (var httpclient = NewClient())
            {
                var result = httpclient.PostAsJsonAsync(FullAddressApi(api), data).Result;
                if (result == null)
                    throw new Exception("result is null!");
                if (result.IsSuccessStatusCode)
                {
                    var s = result.Content.ReadAsStringAsync().Result;
                    if (s != null)
                        callback(JsonConvert.DeserializeObject<T>(s));
                }
                else
                    throw new Exception(result.ReasonPhrase);
            }
        }
        public void Post<T>(string api, Dictionary<string, string> parameters, Action<T> callback)
        {
            using (HttpClient httpClient = new HttpClient())
            {
                var Uri = new StringBuilder();
                Uri.Append(FullAddressApi(api));
                if (parameters != null && parameters.Count > 0)
                {
                    Uri.Append("?");
                    parameters.ToList().ForEach(s => { Uri.Append(s.Key); Uri.Append("="); Uri.Append(s.Value); Uri.Append("&"); });
                    Uri.Remove(Uri.Length -1,1);
                }

                var result =httpClient.PostAsync(Uri.ToString(),null).Result;
                if(result ==null)
                    throw new Exception ("result is null!");
                if(result.IsSuccessStatusCode )
                {
                    var s =result.Content.ReadAsStringAsync().Result ;
                    if(s!=null)
                        callback (JsonConvert.DeserializeObject<T>(s));
                }
            }
        }

        private string FullAddressApi(string api)
        {
            return string.Format("{0}/{1}", _host.TrimEnd(/), api.TrimStart(/));
        }

    }
}

调用代码示例:

using demo.PublicDatas;
using demo.Model;
using demo.ApiClient;
using Newtonsoft.Json;

namespace demo
{
    class Program
    {
        static void Main(string[] args)
        {

            //Login  Demo
            var host = "http://localhost:38362";
            //var api = Api.Login.Login4WinForm;
            var api = "/api/loginapi";
            var loginModel =new LoginModel(){Account ="123",Password ="123",OrgCode ="123"};
            new WebApiClient(host).Post<ActionResult<LoginInfo>, LoginModel>(api, loginModel, result => {

                Console.WriteLine(JsonConvert.SerializeObject(result));
            });



        }
    }
}

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。