ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

C# RestSarp简单使用

2020-07-09 14:02:16  阅读:413  来源: 互联网

标签:cookies string C# request json 简单 RestSarp new RestSharp


1.简介

 RestSharp 是一个基于 .NET 框架的 REST 客户端,RestSharp 是一个轻量的,不依赖任何第三方的组件或者类库的 HTTP 组件,C#使用RestSharp可以快速完成http的网络请求。

2.RestSharp用法

1) 通过请求服务的地址初始化一个RestClient类

string serverUrl="127.0.0.1:8080"
RestClient client = new RestClient(serverUrl);

2)发送get或者post请求(此次请求一个测试登录的页面,密码使用了md5加密)

//页面请求链接为“http://127.0.0.1:8080/test/test.html”
string requestUrl="test/test.do"
RestRequest request = new RestRequest(url, Method.POST);
request.AddParameter("username", username);
request.AddParameter("userpwd", md5(password));
IRestResponse response = client.Execute(request);
IList<RestResponseCookie> cookies = response.Cookies;

3)给request添加cookies

  由于RestSharp没有会话保持,通过client.Execute每次发起的请求都不携带cookies信息,当我们需要某些操作是需要保持页面session时我们就需要给request请求中添加已经获取的cookies,具体代码如下

IList<RestSharpCookie> cookies=response.Cookies;
foreach (RestResponseCookie cookie in cookies)
{
    request.AddCookie(cookie.Name, cookie.Value);
}
return request;

  这样我们就会给需要的reqeust添加上了cookie

4)带json参数并且返回json的post请求

a)是简单的参数时

  可以直接用request.AddParameter(key,value)的形式传入

b)参数是一个类时

class Datas {
            public string username;
            public string password;
            public Datas(string uesrname, string password)
            {
                this.username = username;
                this.password = password;

            }
}//此次为了方便举例写了一个简单的类其他的类对象都可以按下面方法完成
Datas data=new Datas("零度热冰","ldrb");
StringBuilder sb = new StringBuilder();
JavaScriptSerializer json = new JavaScriptSerializer();//使用了System.Web.Script.Serialization.JavaScriptSerializer
json.Serialize(data, sb);
request.AddJsonBody(sb);
//...........
                              

5)将返回的参数反序列化为类对象

JavaScriptSerializer json = new JavaScriptSerializer();
Datas data=json.Deserialize<Datas>(response.Content);

 

标签:cookies,string,C#,request,json,简单,RestSarp,new,RestSharp
来源: https://www.cnblogs.com/lingdurebing/p/ldrb-CSharp-restSharp.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有