欢迎光临
我的个人博客网站

Winform中使用HttpClient与后端api服务进行交互


前端js可以使用ajax、axios发出http请求
在c#中winform、控制台等可以通过WebRequest、WebClient、HttpClient

有关三个类的性能对比大家可以自己搜一下,这里我主要使用和封装了HttpClient类,对于ResultDto大家可以根据所需进行修改或删除

public class HttpHelper     {         private static readonly object LockObj = new object();         private static HttpClient client = null;         private static readonly string BASE_ADDRESS = "http://localhost:1229/";         public HttpHelper()         {             GetInstance();         }         /// <summary>         /// 制造单例         /// </summary>         /// <returns></returns>         public static HttpClient GetInstance()         {             if (client == null)             {                 lock (LockObj)                 {                     if (client == null)                     {                         client = new HttpClient() {                             BaseAddress = new Uri(BASE_ADDRESS)                         };                     }                 }             }             return client;         }         /// <summary>         /// 异步Post请求         /// </summary>         /// <param name="url">请求地址</param>         /// <param name="strJson">传入的数据</param>         /// <returns></returns>         public async Task<string> PostAsync(string url,string strJson)         {             try             {                 HttpContent content = new StringContent(strJson);                 content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");                 HttpResponseMessage res = await client.PostAsync(url,content);                 if (res.StatusCode == System.Net.HttpStatusCode.OK)                 {                     string resMsgStr = await res.Content.ReadAsStringAsync();                     return resMsgStr;                 }                 else                 {                     return null;                 }             }             catch (Exception)             {                 return null;             }         }         /// <summary>         /// 同步Post         /// </summary>         /// <param name="url"></param>         /// <param name="strJson"></param>         /// <returns></returns>         public string Post(string url, string strJson)         {             try             {                 HttpContent content = new StringContent(strJson);                 content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");                 //client.DefaultRequestHeaders.Connection.Add("keep-alive");                 //由HttpClient发出Post请求                 Task<HttpResponseMessage> res = client.PostAsync(url, content);                 if (res.Result.StatusCode == System.Net.HttpStatusCode.OK)                 {                     string resMsgStr = res.Result.Content.ReadAsStringAsync().Result;                     return resMsgStr;                 }                 else                 {                     return null;                 }             }             catch (Exception ex)             {                 return null;             }         }         /// <summary>         /// 异步Post请求         /// </summary>         /// <typeparam name="TResult">返回参数的数据类型</typeparam>         /// <param name="url">请求地址</param>         /// <param name="data">传入的数据</param>         /// <returns></returns>         public async Task<TResult> PostAsync<TResult>(string url, object data)         {             try             {                 var jsonData = JsonConvert.SerializeObject(data);                 HttpContent content = new StringContent(jsonData);                 content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");                 HttpResponseMessage res = await client.PostAsync(url, content);                 if (res.StatusCode == System.Net.HttpStatusCode.OK)                 {                     string resMsgStr = await res.Content.ReadAsStringAsync();                     var result= JsonConvert.DeserializeObject<ResultDto<TResult>>(resMsgStr);                     return result != null ? result.Data : default;                 }                 else                 {                     MessageBox.Show(res.StatusCode.ToString());                     return default;                 }             }             catch (Exception ex)             {                 MessageBox.Show(ex.Message);                 return default;             }         }         /// <summary>         /// 同步Get请求         /// </summary>         /// <param name="url">请求地址</param>         /// <returns></returns>         public string Get(string url)         {             try             {                 var responseString = client.GetStringAsync(url);                 return responseString.Result;             }             catch (Exception ex)             {                 return null;             }         }         /// <summary>         /// 异步Get请求         /// </summary>         /// <param name="url">请求地址</param>         /// <returns></returns>         public async Task<string> GetAsync(string url)         {             try             {                 var responseString =await client.GetStringAsync(url);                 return responseString;             }             catch (Exception ex)             {                 return null;             }         }         /// <summary>         /// 异步Get请求         /// </summary>         /// <typeparam name="TResult">返回参数的数据</typeparam>         /// <param name="url">请求地址</param>         /// <returns></returns>         public async Task<TResult> GetAsync<TResult>(string url)         {             try             {                 var resMsgStr = await client.GetStringAsync(url);                 var result = JsonConvert.DeserializeObject<ResultDto<TResult>>(resMsgStr);                 return result != null ? result.Data : default;             }             catch (Exception ex)             {                 return default(TResult);             }         }      }      public class ResultDto<TResult>     {         public string Msg { get; set; }         public TResult Data { get; set; }         public bool Success { get; set; }     } } 

记录我在博客园发布的第一篇文章,后续会把本人在csdn的文章都迁移过来
https://blog.csdn.net/hyx1229

赞(0) 打赏
未经允许不得转载:张拓的天空 » Winform中使用HttpClient与后端api服务进行交互
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

专业的IT技术经验分享 更专业 更方便

联系我们本站主机

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏