Cuture.Http 2.8.1

dotnet add package Cuture.Http --version 2.8.1                
NuGet\Install-Package Cuture.Http -Version 2.8.1                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Cuture.Http" Version="2.8.1" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add Cuture.Http --version 2.8.1                
#r "nuget: Cuture.Http, 2.8.1"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install Cuture.Http as a Cake Addin
#addin nuget:?package=Cuture.Http&version=2.8.1

// Install Cuture.Http as a Cake Tool
#tool nuget:?package=Cuture.Http&version=2.8.1                

Cuture.Http

Intro

用于快速进行Http请求的链式拓展方法库。

Features

  • 主要为针对stringUri对象的拓展方法,快速构建请求;
  • 包含对System.Net.Http.HttpResponseMessage的拓展方法,也可以配合原始HttpClient使用;
  • 连接复用,内部使用System.Net.Http.HttpClient进行请求;
  • 使用链式的拓展方法可以配置请求的绝大多数信息;
  • Http相关的常用工具类及拓展方法;
  • DynamicJSON(基于dynamicjson快速访问);
  • 请求构建工具,直接使用原始请求数据(如从Fiddler中复制)复现请求;
  • 目标框架为.Net6.0+;

Note


如何使用

安装Nuget包

Install-Package Cuture.Http
  1. 创建请求
var request = "http://www.domain.com/api".CreateHttpRequest();
  1. 设置请求
 request.UseUserAgent(UserAgents.FireFox)
        .AddHeader("header1", "header1Value")
        .UsePost()
        .TimeOut(3000)
        .WithCancellation(token)
        //进行其他的一些请求设置等
        .WithFormContent($"key={value.UrlEncode()}");
  1. 请求并获取结果
var response = await request.TryGetAsStringAsync();
Console.WriteLine($"response:{response.Data}");
  • 请求方法包括直接返回请求结果的方法 GetAsBytesAsyncGetAsJsonDocumentAsyncGetAsObjectAsync<T>GetAsStringAsyncGetAsDynamicJsonAsync 和内部吞掉异常的 TryGetAsBytesAsyncTryGetAsJsonDocumentAsyncTryGetAsObjectAsync<T>TryGetAsStringAsyncTryGetAsDynamicJsonAsync ;
  • GetAsJsonDocumentAsync 将返回以 System.Text.Json.JsonDocument.Parse 转换请求结果后的 JsonDocument 对象;
  • GetAsObjectAsync<T> 将返回以 System.Text.Json.JsonSerializer.DeserializeAsync<T> 反序列化请求结果后的 T 对象;
  • GetAsDynamicJsonAsync 将返回一个基于 JSON 的可动态访问的 dynamic 对象;

使用示例

获取网页数据

var response = await "http://www.baidu.com".CreateHttpRequest()
                                            .GetAsStringAsync();
Console.WriteLine(response);

获取并解析接口数据

var url = "https://docs.microsoft.com/api/privacy/cookieConsent?locale=zh-cn";
var response = await url.CreateHttpRequest()
                        .GetAsJsonDocumentAsync();
Console.WriteLine(response["message"]["message"]);

使用 dynamic:

var url = "https://docs.microsoft.com/api/privacy/cookieConsent?locale=zh-cn";
var response = await url.CreateHttpRequest()
                        .GetAsDynamicJsonAsync();
Console.WriteLine(response.message.message);

需要进度的下载

var url = "https://download.visualstudio.microsoft.com/download/pr/a16689d1-0872-4ef9-a592-406d3038d8f7/cf4f84504385a599f0cb6a5c113ccb34/aspnetcore-runtime-3.1.0-win-x64.exe";
try
{
    using var stream = File.OpenWrite("d:\\runtime.exe");
    await url.CreateHttpRequest()
             .DownloadToStreamWithProgressAsync((contentLength, downloaded) =>
             {
                 if (contentLength > 0)
                 {
                     Console.WriteLine($"已下载:{downloaded / 1024} kb,进度 {(((float)downloaded / contentLength) * 100).Value.ToString("F")} %");
                 }
                 else
                 {
                     Console.WriteLine($"已下载:{downloaded / 1024} kb");
                 }
             }, stream, 1024 * 1024);
}
catch (Exception ex)
{
    Console.WriteLine($"下载失败:{ex}");
}

从原始数据构建请求

  • 使用从各种抓包工具中复制的原始数据,快速构建等价请求
var rawBase64Str = "R0VUIGh0dHA6Ly9kZXRlY3Rwb3J0YWwuZmlyZWZveC5jb20vc3VjY2Vzcy50eHQgSFRUUC8xLjENCkhvc3Q6IGRldGVjdHBvcnRhbC5maXJlZm94LmNvbQ0KVXNlci1BZ2VudDogTW96aWxsYS81LjAgKFdpbmRvd3MgTlQgMTAuMDsgV2luNjQ7IHg2NDsgcnY6ODQuMCkgR2Vja28vMjAxMDAxMDEgRmlyZWZveC84NC4wDQpBY2NlcHQ6ICovKg0KQWNjZXB0LUxhbmd1YWdlOiB6aC1DTix6aDtxPTAuOCx6aC1UVztxPTAuNyx6aC1ISztxPTAuNSxlbi1VUztxPTAuMyxlbjtxPTAuMg0KQWNjZXB0LUVuY29kaW5nOiBnemlwLCBkZWZsYXRlDQpDYWNoZS1Db250cm9sOiBuby1jYWNoZQ0KUHJhZ21hOiBuby1jYWNoZQ0KRE5UOiAxDQpDb25uZWN0aW9uOiBrZWVwLWFsaXZlDQoNCg==";
var request = RequestBuildTool.FromRaw(rawBase64Str);
//进行其他的一些请求设置等,覆盖原始的请求设置
var result = await request.TryGetAsStringAsync();
  • 仅从原始数据中加载指定部分
//仅读取请求头
request.LoadHeadersFromRaw(rawBase64Str);
//仅读取请求内容
request.LoadContentFromRaw(rawBase64Str);
//读取请求头和内容
request.LoadHeadersAndContentFromRaw(rawBase64Str);

DynamicJSON

支持访问与修改

using Cuture.Http.DynamicJSON;

//使用对象创建
var json = JSON.create(new object());
Console.WriteLine(json.Prop1.Array1[0].Prop2);

//使用json字符串创建
json = JSON.parse("{}");
Console.WriteLine(json.Prop1.Array1[0].Prop2);

判断是否为未定义字段

json.notexistfield == JSON.Undefined

JSON.isUndefined(json.notexistfield)
IEnumerable

使用IEnumerable以支持使用Linq, (C#不支持实现dynamic的接口,所以需要额外的转换)

//遍历Array
//显式赋值类型
IEnumerable<dynamic> enumerable = json.Array;
//通过IDynamicEnumerable
var enumerable = ((IDynamicEnumerable)json.Array).AsEnumerable();

//遍历属性
//显式赋值类型
IEnumerable<KeyValuePair<string, dynamic?>> enumerable = json;
//通过IDynamicKeyValueEnumerable
var enumerable = ((IDynamicKeyValueEnumerable)json).AsEnumerable();

部分其它工具拓展示例

Base64编码
"https://dotnet.microsoft.com/".EncodeBase64();
//aHR0cHM6Ly9kb3RuZXQubWljcm9zb2Z0LmNvbS8=
"aHR0cHM6Ly9kb3RuZXQubWljcm9zb2Z0LmNvbS8=".DecodeBase64();
//https://dotnet.microsoft.com/
UrlEncode
"keyword关键词".UrlEncode();
//keyword%e5%85%b3%e9%94%ae%e8%af%8d
"keyword%e5%85%b3%e9%94%ae%e8%af%8d".UrlDecode();
//keyword关键词
随机UA
UserAgents.RandomUserAgent();
var cookie = "lang=en-US; Path=/; Max-Age=2147483647 i_like_gogs=d38e69bb16e9080d; Path=/; HttpOnly _csrf=Zxnf2GNhwYoZUONx6ylflfFS0CI6MTU3ODExNzU2NzU4MDM0NjEzMg%3D%3D; Path=/; Expires=Sun, 05 Jan 2020 05:59:27 GMT; HttpOnly";
CookieUtility.Clean(cookie);
//lang=en-US; i_like_gogs=d38e69bb16e9080d; _csrf=Zxnf2GNhwYoZUONx6ylflfFS0CI6MTU3ODExNzU2NzU4MDM0NjEzMg%3D%3D;
Product Compatible and additional computed target framework versions.
.NET net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 is compatible.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • net6.0

    • No dependencies.
  • net7.0

    • No dependencies.
  • net8.0

    • No dependencies.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on Cuture.Http:

Package Downloads
Cuture.Http.NewtonsoftJson

用于 Cuture.Http 库的 Newtonsoft.Json 功能支持

GitHub repositories (1)

Showing the top 1 popular GitHub repositories that depend on Cuture.Http:

Repository Stars
stratosblue/IntelliSenseLocalizer
a tool for generate .net Localized IntelliSense files. 用于生成本地化 .net IntelliSense文件的工具。
Version Downloads Last updated
2.8.1 9,202 8/11/2024
2.8.0 18,978 11/15/2023
2.7.2 17,245 5/20/2023
2.7.1 9,775 12/14/2022
2.7.0 1,138 12/3/2022
2.6.0 4,423 10/7/2022
2.5.0 7,263 7/3/2022
2.5.0-alpha0001 1,732 6/11/2022
2.1.1 12,074 12/13/2021
2.1.0 4,152 10/23/2021
2.0.6 3,227 9/14/2021
2.0.5 2,524 8/16/2021
2.0.4 1,200 8/7/2021
2.0.3 4,968 6/19/2021
2.0.2 3,944 5/14/2021
2.0.1 3,484 4/14/2021
2.0.0 2,949 3/18/2021
2.0.0-alpha0004 1,462 3/6/2021
2.0.0-alpha0003 358 3/6/2021
2.0.0-alpha0002 732 3/1/2021
2.0.0-alpha0001 254 2/22/2021
1.4.1 3,898 1/23/2021
1.4.0 3,434 12/22/2020
1.3.8 501 11/14/2020
1.3.7 420 11/12/2020
1.3.6 551 10/31/2020
1.3.2 490 9/18/2020
1.3.1 508 7/27/2020
1.3.0 522 4/23/2020
1.2.0 540 4/6/2020
1.1.1 572 2/10/2020
1.1.0 612 1/8/2020
1.0.3 714 1/5/2020
1.0.2 632 1/4/2020
1.0.1 500 1/3/2020
1.0.0 518 12/30/2019