新公司上班第二周,开始进军.Net Core,这方面的东西比较新,所以已经封装好的东西比较少,比如HttpClien之类的开源类库,找了NuGet好久,没有找到,所以先写个简陋的来用着先。

using System.Threading.Tasks;
using System.Net.Http;
using Newtonsoft.Json;
using System.Net.Http.Headers; /// <summary>
/// Http Method Helper
/// </summary>
public static class HttpHelper
{
private static HttpClient instance = null;
public static HttpClient GetClient()
{
if (instance == null)
instance = new HttpClient();
return instance;
} /// <summary>
/// Get Method
/// </summary>
public static async Task<T> Get<T>(string url)
{
try
{
var client = GetClient();
var responseMsg = await client.GetAsync(url);
if (responseMsg.IsSuccessStatusCode)
{
string strJson = await responseMsg.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<T>(strJson);
}
else
{
return default(T);
} }
catch
{
instance = new HttpClient();
return default(T);
}
} /// <summary>
/// Post Method
/// </summary>
public static async Task<T> Post<T>(string url, dynamic para)
{
try
{
if (para != null)
{
var requestJson = JsonConvert.SerializeObject(para);
HttpContent httpContent = new StringContent(requestJson);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var client = GetClient(); var responseJson = await client.PostAsync(url, httpContent).Result.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<T>(responseJson);
}
return default(T);
}
catch
{
instance = new HttpClient();
return default(T);
}
}
}

调用测试:

//=======================================================
//                  .----.
//               _.'__    `.
//           .--(^)(^^)---/#\
//         .' @          /###\
//         :         ,   #####
//          `-..__.-' _.-\###/
//                `;_:    `"'
//              .'"""""`.
//             /,  ya ,\\
//            //向上吧!409  \\
//            `-._______.-'
//            ___`. | .'___
//           (______|______)
//=======================================================

最新文章

  1. git 创建分支 并 提交到远程分支
  2. sed 技巧
  3. Binary Tree Non-recursive Traversal
  4. Maven 项目导入错误解决。
  5. Codeforce 493c
  6. ZOJ 3597 Hit the Target! (线段树扫描线 -- 矩形所能覆盖的最多的点数)
  7. SQL Server 高性能写入的一些总结(转)
  8. springMVC+MyBatis+Spring 整合(3)
  9. JavaScript网站设计实践(六)编写live.html页面 改进表格显示
  10. C51 延时程序
  11. [Angular 2] Async Http
  12. poj1511/zoj2008 Invitation Cards(最短路模板题)
  13. js之with
  14. 测试web网站兼容性的方法
  15. 网络攻击技术开篇——SQL Injection
  16. 笔记-CGRectInset CGRectoffset UIEdgeInsetsInsetRect 这三个函数的使用情况
  17. MySQL8.0
  18. Oracle 12C执行root.sh CLSRSC-119 CRS-8503 CLSRSC-366
  19. uiautomatorviewer工具的安装与使用
  20. python基础之作业3----三级菜单小练习

热门文章

  1. 跟着刚哥梳理java知识点——包装类(十)
  2. 【shell编程基础3】shell编程的组合应用之二:管道及其命令
  3. 海康/大华 IpCamera RTSP地址和格式
  4. java抽象类和抽象方法之间的关系
  5. JDK源码之PriorityQueue源码剖析
  6. 关于String类和String[]数组的获取长度方法细节
  7. bzoj4818 [Sdoi2017]序列计数
  8. 写个神经网络,让她认得我`(๑•ᴗ•๑)(Tensorflow,opencv,dlib,cnn,人脸识别)
  9. JSP动态员工登陆案例
  10. 使用Blender的UV映射制作一个地球