HttpLib很好用的Http请求类库,HttpLib 可以用来简化在 C# 应用中异步的访问 Web 服务的操作。
支持很多种方法:
using JumpKick.HttpLib.Builder;
namespace JumpKick.HttpLib
{
public static class Http
{
public static RequestBuilder Delete(string url);
public static RequestBuilder Get(string url);
public static RequestBuilder Head(string url);
public static RequestBuilder Patch(string url);
public static RequestBuilder Post(string url);
public static RequestBuilder Put(string url);
}
}
using Redslide.HttpLib
1、获取网页数据:
Http.Get("https://jthorne.co.uk/httplib").OnSuccess(result =>
{
Console.Write(result);
}).OnFail(webexception =>
{
Console.Write(webexception.Message);
}).Go();
如果想通过GET方式传参并获取数据,传参方式只能是在链接后拼接字符串形式,不可以Form或Body形式传参,这两种方式只适用于POST。
Http.Get("https://jthorne.co.uk/httplib?name={0}&userid={1}", "Jame", "23").OnSuccess(result =>
{
Console.Write(result);
}).OnFail(webexception =>
{
Console.Write(webexception.Message);
}).Go();
2、下载
Http.Get("https://jthorne.co.uk/httplib").DownloadTo(@"C:\httplib.html", onProgressChanged: (bytesCopied,totalBytes) =>;
{
if (totalBytes.HasValue)
{
("Downloaded: " + (bytesCopied/totalBytes)*100 + "%");
}
Console.Write("Downloaded: " + bytesCopied.ToString() + " bytes");
},
onSuccess: (headers) =>
{
UpdateText("Download Complete");
}).Go();
1、Form形式传参
Http.Post("https://jthorne.co.uk/httplib").Form(new { name = "James", username = "j6mes" }).OnSuccess(result =>
{
Console.Write(result);
}).OnFail(webexception =>
{
Console.Write(webexception.Message);
}).Go();
2、Body形式传参(json格式)
public int m_userId; //下发人id
public string m_title; //下发任务标题
public string m_content; //下发任务内容
Http.Post("https://jthorne.co.uk/httplib").Body("application/json", "{ userId :m_userId,title : m_title,content : m_content}"
).OnSuccess(result =>
{
Dialog.Information("成功");
Dialog.Information("result:" + result);
}).OnFail(result =>
{
Dialog.Information("失败");
Dialog.Information("result:" + result);
}).Go();
3、form-urlencoded方式传参
Http.Post("https://jthorne.co.uk/httplib").Body("name=admin"
).OnSuccess(result =>
{
Console.Write(result);
}).OnFail(result =>
{
Console.Write(webexception.Message);
}).Go();
4、Upload上传文件
Http.Post("https://jthorne.co.uk/httplib")
.Upload(files:
new[] {
new NamedFileStream("myfile", "photo.jpg", "application/octet-stream", File.OpenRead(@"C:\photo.jpg"))
}).Go();
Http.Post("https://jthorne.co.uk/httplib").Form(new { name = "James", username = "j6mes" }
).Upload(
files:
new[] {
new NamedFileStream("myfile", "photo.jpg", "application/octet-stream", File.OpenRead(@"C:\photo.jpg"))
},
onProgressChanged:
(bytesSent, totalBytes) =>
{
Console.WriteLine("Uploading: " + (bytesSent / totalBytes)*100 + "% completed");
})
.OnSuccess(result=>
{
Console.WriteLine(result);
}).Go();
四、Delete用法
Http.Delete("https://jthorne.co.uk/httplib").Go();
最后附几个链接:
1、HttpLib官网链接,里面有HttpLib的各种用法,以及github的源码地址等。
2、参考了另一博主的博客,为表示感谢,也给出链接