EasyHttp基本使用

来源:互联网 发布:许小年水平怎么样知乎 编辑:程序博客网 时间:2024/05/16 19:49

由于在用C#请求DRF的API时遇到了认证问题,只好用个第三方的包来解决这个问题。

同时了解到了HttpLib和EasyHttp,然后决定使用EasyHttp。

项目的地址:https://github.com/EasyHttp/EasyHttp。在VS上可以直接用NuGet安装。

主要使用的内容在EasyHttp.Http中。

using EasyHttp.Http;
下面是一个get请求的示例:

HttpClient client = new HttpClient();var response = client.Get("http://127.0.0.1:8000/");Console.WriteLine(response.StatusCode);Console.WriteLine(response.RawText);
要建立一个请求客户端,就使用HttpClient类。

之后调用该对象的Get/Post/Put/Patch/Pelete等方法发送一个请求,并返回一个HttpResponse对象。

不同的请求方法需要传入的参数不同。

HttpResponse Get(string uri)  //GET请求,传入URLHttpResponse Head(string uri)  //HEAD请求HttpResponse Options(string uri)  //OPTIONS请求HttpResponse Post(string uri, string content, string contentType)  //POST请求之一,传入内容字符串content,同时需要一个contentType类型HttpResponse Post(string uri, IDictionary<string,object> data)  //POST请求之二,传入一个POST内容的字典HttpResponse Put(string uri, string content, string contentType)  //PUT请求HttpResponse Patch(string uri, string content, string contentType)  //PATCH请求HttpResponse Delete(string uri)  //DELETE请求

HttpResponse对象包含response的所有信息,其中比较重要的有:

response.ContentType;  //ContentTyperesponse.Cookies;  //Cookiesresponse.RawText;  //Contentresponse.StatusCode;  //HTTP状态码response.StatusDescription;  //HTTP状态描述response.RawHeaders;  //Headersresponse.CharacterSet;   //字符集
另外,如果需要访问request的信息,使用HttpClient的request属性。该属性返回一个HttpRequest对象。

如果需要设置认证功能,那么通过HttpRequest完成。

request.SetBasicAuthentication(username, password);request.ForceBasicAuth = true;


1 0
原创粉丝点击