c#: 使用restsharp發送http請求、下載文件

環境:

  • 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}");
                }

            }
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章