HttpClien Get&Post
2024-09-09 18:28:58
新公司上班第二周,开始进军.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 \\
// `-._______.-'
// ___`. | .'___
// (______|______)
//=======================================================
最新文章
- git 创建分支 并 提交到远程分支
- sed 技巧
- Binary Tree Non-recursive Traversal
- Maven 项目导入错误解决。
- Codeforce 493c
- ZOJ 3597 Hit the Target! (线段树扫描线 -- 矩形所能覆盖的最多的点数)
- SQL Server 高性能写入的一些总结(转)
- springMVC+MyBatis+Spring 整合(3)
- JavaScript网站设计实践(六)编写live.html页面 改进表格显示
- C51 延时程序
- [Angular 2] Async Http
- poj1511/zoj2008 Invitation Cards(最短路模板题)
- js之with
- 测试web网站兼容性的方法
- 网络攻击技术开篇——SQL Injection
- 笔记-CGRectInset CGRectoffset UIEdgeInsetsInsetRect 这三个函数的使用情况
- MySQL8.0
- Oracle 12C执行root.sh CLSRSC-119 CRS-8503 CLSRSC-366
- uiautomatorviewer工具的安装与使用
- python基础之作业3----三级菜单小练习
热门文章
- 跟着刚哥梳理java知识点——包装类(十)
- 【shell编程基础3】shell编程的组合应用之二:管道及其命令
- 海康/大华 IpCamera RTSP地址和格式
- java抽象类和抽象方法之间的关系
- JDK源码之PriorityQueue源码剖析
- 关于String类和String[]数组的获取长度方法细节
- bzoj4818 [Sdoi2017]序列计数
- 写个神经网络,让她认得我`(๑•ᴗ•๑)(Tensorflow,opencv,dlib,cnn,人脸识别)
- JSP动态员工登陆案例
- 使用Blender的UV映射制作一个地球