zoukankan      html  css  js  c++  java
  • 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);
  • 相关阅读:
    将10进制数字转成62进制数字(转)
    admin添加用户时报错:(1452, 'Cannot add or update a child row: a foreign key constraint fails (`mxonline`.`django_admin_l
    Django admin 中抛出 'WSGIRequest' object has no attribute 'user'的错误
    分布式爬虫
    Scrapy之CrawlSpider
    Scrapy之Cookie和代理
    Scrapy核心组件
    scrapy之持久化存储
    Scrapy框架的基本使用
    爬虫之request模块高级
  • 原文地址:https://www.cnblogs.com/lingdurebing/p/ldrb-CSharp-restSharp.html
Copyright © 2011-2022 走看看