• c#: 使用restsharp发送http请求、下载文件


    原文地址:https://blog.csdn.net/u010476739/article/details/105216936

    环境:

    vs2019 16.5.1
    aspnetcore 3.1.1
    fiddler
    restsharp 106.10.1
    说明:
    要测试restsharp的功能,首先需要了解http传参和下载上传文件的原理,请参考:
    c#:从http请求报文看http协议中参数传递的几种方式
    c#使用Http上传下载文件

    一、restsharp介绍
    RestSharp是一个轻量的,不依赖任何第三方的组件或者类库的Http的组件。RestSharp具体以下特性:
    1、支持.NET 3.5+,Silverlight 4, Windows Phone 7, Mono, MonoTouch, Mono for Android, Compact Framework 3.5,.NET Core等
      2、通过NuGet方便引入到任何项目 ( Install-Package restsharp )
      3、可以自动反序列化XML和JSON
      4、支持自定义的序列化与反序列化
      5、自动检测返回的内容类型
      6、支持HTTP的GET, POST, PUT, HEAD, OPTIONS, DELETE等操作
      7、可以上传多文件
      8、支持oAuth 1, oAuth 2, Basic, NTLM and Parameter-based Authenticators等授权验证等
      9、支持异步操作
      10、极易上手并应用到任何项目中
    以上是RestSharp的主要特点,通用它你可以很容易地用程序来处理一系列的网络请求(GET, POST, PUT, HEAD, OPTIONS, DELETE),并得到返回结果。
    restsharp官网:http://restsharp.org/

    二、首先准备webapi项目
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Logging;

    namespace testweb.Controllers
    {
    [ApiController]
    [Route("[controller]/[action]")]
    public class TestController : ControllerBase
    {
    public async Task<IEnumerable<object>> TestGet()
    {
    return new object[] { new { Name = "小明", age = 20 }, new { Name = "小花", age = 18 } };
    }

    public async Task<IEnumerable<object>> TestPost()
    {
    return new object[] { new { Name = "post小明", age = 20 }, new { Name = "post小花", age = 18 } };
    }

    [HttpGet]
    [HttpPost]
    public async Task<string> TestUrlPara([FromQuery]string name, [FromQuery]int? age)
    {
    return $"hello {name},你{age}岁了!";
    }


    [HttpPost]
    public async Task<string> TestPostUrlFormUrlencoded([FromForm]string name, [FromForm]int? age)
    {
    return $"hello {name},你{age}岁了!";
    }

    [HttpPost]
    public async Task<string> TestPostUrlFormData([FromForm]string name, [FromForm]int? age)
    {
    return $"hello {name},你{age}岁了,你上传了{Request.Form.Files.Count}个文件!";
    }

    [HttpPost]
    public string TestBodyJson([FromBody]User user)
    {
    if (user == null) return "user is null.";
    return Newtonsoft.Json.JsonConvert.SerializeObject(user);
    }

    [HttpGet]
    public IActionResult TestDownLoad()
    {
    var filepath = @"C:\Users\AUAS\Pictures\百度下载图片\timg.jpg";
    FileStream fs = new FileStream(filepath, FileMode.Open);
    return File(fs, "application/octet-stream", "test.png");
    }
    }
    public class User
    {
    public string name { get; set; }
    public int? id { get; set; }
    }
    }

    三、开始测试restsharp发送各种类型http请求和下载文件
    3.1 首先nuget包引入restsharp


    3.2 直接看测试代码
    using RestSharp;
    using System;
    using System.IO;

    namespace restsharpdemo
    {
    class Program
    {
    private static RestClient client = new RestClient("http://localhost:5000/");
    static void Main(string[] args)
    {
    //TestGet();
    //TestPost();
    //TestUrlPara();
    //TestPostUrlFormUrlencoded();
    //TestPostUrlFormData();
    //TestBodyJson();
    //TestDownLoad();
    Console.WriteLine("Hello World!");
    Console.ReadLine();
    }

    /// <summary>
    /// 测试下载文件
    /// </summary>
    private static void TestDownLoad()
    {
    string tempFile = Path.GetTempFileName();
    using (var writer = File.OpenWrite(tempFile))
    {
    var req = new RestRequest("test/TestDownLoad", Method.GET);
    req.ResponseWriter = responseStream =>
    {
    using (responseStream)
    {
    responseStream.CopyTo(writer);
    }
    };
    var response = client.DownloadData(req);
    }
    }

    /// <summary>
    /// 测试传递application/json类型参数
    /// </summary>
    private static void TestBodyJson()
    {
    var req = new RestRequest("test/TestBodyJson", Method.POST);
    req.AddJsonBody(new { name = "小花", id = 23 });
    var res = client.Execute(req);
    if (res.IsSuccessful)
    {
    Console.WriteLine($"成功:{res.Content}");
    }
    else
    {
    if (res.StatusCode == 0)
    {
    Console.WriteLine($"失败:网络错误:{res.ErrorMessage}");
    }
    else
    {
    Console.WriteLine($"失败:{(int)res.StatusCode}-{res.StatusDescription}");
    }
    }
    }

    /// <summary>
    /// 测试传递post multipart/form-data参数
    /// </summary>
    private static void TestPostUrlFormData()
    {
    var req = new RestRequest("test/TestPostUrlFormData", Method.POST);
    req.AlwaysMultipartFormData = true;
    req.AddParameter("name", "小明");
    req.AddParameter("age", "20");
    req.AddFile("file1", @"C:\Users\AUAS\Pictures\百度下载图片\timg.jpg");
    var res = client.Execute(req);
    if (res.IsSuccessful)
    {
    Console.WriteLine($"成功:{res.Content}");
    }
    else
    {
    if (res.StatusCode == 0)
    {
    Console.WriteLine($"失败:网络错误:{res.ErrorMessage}");
    }
    else
    {
    Console.WriteLine($"失败:{(int)res.StatusCode}-{res.StatusDescription}");
    }
    }
    }

    /// <summary>
    /// 测试传递post application/x-www-form-urlencoded参数
    /// </summary>
    private static void TestPostUrlFormUrlencoded()
    {
    var req = new RestRequest("test/TestPostUrlFormUrlencoded", Method.POST);
    //将参数编码后加到url上
    req.AddHeader("Content-Type", "application/x-www-form-urlencoded");
    req.AddParameter("name", "小明");
    req.AddParameter("age", "20");
    var res = client.Execute(req);
    if (res.IsSuccessful)
    {
    Console.WriteLine($"成功:{res.Content}");
    }
    else
    {
    if (res.StatusCode == 0)
    {
    Console.WriteLine($"失败:网络错误:{res.ErrorMessage}");
    }
    else
    {
    Console.WriteLine($"失败:{(int)res.StatusCode}-{res.StatusDescription}");
    }
    }
    }

    /// <summary>
    /// 测试传递url参数
    /// </summary>
    private static void TestUrlPara()
    {
    var req = new RestRequest("test/TestUrlPara", Method.GET);
    req = new RestRequest("test/TestUrlPara", Method.POST);
    //将参数编码后加到url上
    req.AddParameter("name", "小明");
    req.AddParameter("age", "18");
    var res = client.Get(req);
    if (res.IsSuccessful)
    {
    Console.WriteLine($"成功:{res.Content}");
    }
    else
    {
    if (res.StatusCode == 0)
    {
    Console.WriteLine($"失败:网络错误:{res.ErrorMessage}");
    }
    else
    {
    Console.WriteLine($"失败:{(int)res.StatusCode}-{res.StatusDescription}");
    }
    }
    }

    /// <summary>
    /// 测试简单post
    /// </summary>
    private static void TestPost()
    {
    var req = new RestRequest("test/testpost", Method.POST);
    var res = client.Post(req);
    if (res.IsSuccessful)
    {
    Console.WriteLine($"成功:{res.Content}");
    }
    else
    {
    if (res.StatusCode == 0)
    {
    Console.WriteLine($"失败:网络错误:{res.ErrorMessage}");
    }
    else
    {
    Console.WriteLine($"失败:{(int)res.StatusCode}-{res.StatusDescription}");
    }

    }
    }

    /// <summary>
    /// 测试简单get
    /// </summary>
    private static void TestGet()
    {
    var req = new RestRequest("test/testget", Method.GET);
    var res = client.Get(req);
    if (res.IsSuccessful)
    {
    Console.WriteLine($"成功:{res.Content}");
    }
    else
    {
    if (res.StatusCode == 0)
    {
    Console.WriteLine($"失败:网络错误:{res.ErrorMessage}");
    }
    else
    {
    Console.WriteLine($"失败:{(int)res.StatusCode}-{res.StatusDescription}");
    }

    }
    }
    }
    }
    ————————————————
    版权声明:本文为CSDN博主「jackletter」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
    原文链接:https://blog.csdn.net/u010476739/article/details/105216936

  • 相关阅读:
    典型相关性分析(刷题)
    轻音少女美图分享
    动漫美景
    linux下安装redis(全操作)
    前端限制对后端的请求频率
    idea自定义java方法的注释模板
    sql 语句,判断某个值在某个字段中是否存在,存在返回1,不存在返回0
    Error: Module not specified
    解决sql语句中DISTINCT和order by的冲突
    将后端传来的数据放入ul中
  • 原文地址:https://www.cnblogs.com/lizhigang/p/15523232.html
Copyright © 2020-2023  润新知