• C# RestSarp简单使用


    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);
  • 相关阅读:
    生成Ipa安装包的plist文件后生成下载链接
    ssh_key登录服务器,免密码登录
    Ruby中类的进阶(继承,private, public, protect)
    Ruby中的类
    Redis- redis.conf
    Active Job 基础
    rails框架配置
    rails中使用CarrierWave实现文件上传的功能
    Flask-SQLAlchemy
    Linux自动共享USB设备:udev+Samba
  • 原文地址:https://www.cnblogs.com/lingdurebing/p/ldrb-CSharp-restSharp.html
Copyright © 2020-2023  润新知