XIKEW.COM - 实用教程 - (4)LinkCore插件开发之HttpClient&JSON - 实用教程,WebMain项目为例 - HttpClient解决了三方接口调用的问题,JSON可以简单方便的处理回的数据

[已过时] (4)LinkCore插件开发之HttpClient&JSON
LINKCORE NETCORE 4/18/2020 1:31:10 PM 阅读:4

HttpClient解决了三方接口调用的问题,JSON可以简单方便的处理回的数据

注意

LINKCORE已经支持到 NET5.0+ 本文章只使用NET3.0

LinkCore?

点击查看介绍

提前准备

  1. 参考路由设置新建一个 WebMain 的路由项目
  2. 或者你也可以直接 WebMain 或 WPFMain 根目录下的 LinkCore.Interface.dll

这里用WebMain项目为例

推荐使用性能更好的 IHttp

//创建一个Request 对象(必须指定URL)
IRequestUnit httpClient = IHttp.Instance.CreateRequest("https://xxx.com");

//增加头部
httpClient.AddHeaders("Content-Type", "application/json");

//指定超时时间
httpClient.SetTimeOut(5000);

//启用调试模式
httpClient.SetDebug(true);

//设置AcceptEncoding
httpClient.SetAcceptEncoding("gzip");

//设置Cookies
httpClient.SetCookies("https://xxx.com", "");

//启用KeepAlive模式
httpClient.SetConnectionKeepAlive(true)

//Get传参
var result = httpClient.Get();

//Post传参
var result = httpClient.Post(postData);

IHttpClient Get / Post

//全局设置超时时间 默认为10秒
IHttpClient.Instance.SetTimeOut(10);

//全局开启调试模式
IHttpClient.Instance.SetDebug(true);

//启用Keep-Alive
IHttpClient.Instance.ConnectionKeepAlive();

//私有实例
IHttpClient httpclient = IHttpClient.CreateInstance();

//获取底层HttpClient
var client = httpclient.GetClient();

string url = "http://xxx.com/Api";
Dictionary<string, string> headers = new Dictionary<string, string>();

//Get
string result = httpclient.Get(url: url, headers:headers);

//Post
string data = "";
string result = httpclient.Post(url: url, data:data, headers:headers);

注意:

  1. IHttpClient.Instance是以全局单例模式运行的, 所以对其进行的操作会影响到全局

  2. IHttpClient默认启动了SSL忽略

  3. LINUX下运行的项目可能会遇到报错,这里查看解决方案 The handler does not support custom handling of certificates with this combination of libcurl (7.29.0) and its SSL backend

JSON 相关操作

//将对象转为一个json字符串
string jsonStr = JSON.Stringify(jsonObj);

//将json字符串转为对象
var jsonObj = JSON.Parse(jsonStr);

//提取 String
string jsonString = JSON.GetString(jsonObj.jsonString);

//获取 Int
bool jsonBool = JSON.GetBoolen(jsonObj.jsonBool);

//获取 Int
int jsonInt = JSON.GetInt(jsonObj.jsonInt);

//获取 Double
Double jsonDouble = JSON.GetDouble(jsonObj.jsonDouble);

//获取 GetDecimal
Decimal jsonDecimal = JSON.GetDecimal(jsonObj.jsonDecimal);

//获取 GetDateTime
DateTime jsonDateTime = JSON.GetDateTime(jsonObj.jsonDateTime)

//将json字符串转为字典
Dictionary<string, object> dict = JSON.ToDictionary(jsonStr);

//将模型转为字典
Dictionary<string, object> dict = JSON.ToDictionary(model);

//将JsonArray转化为List<T>
List<T> list = JSON.GetList(jsonArray);

//将字典转为模型
UserModel model = JSON.To<UserModel>(dict);

//将json字符串转为模型
UserModel model = JSON.To<UserModel>(jsonStr);

//快速输出json字符串
string jsonStr = JSON.String("Code:0000", "Message:Success")

string jsonStr = JSON.String(new []{ "Code", "0000" }, new []{ "Data", Obj  } );

更优方案: 如果要追求更高性能的JSON操作,可以使用 System.Text.Json