[C#]使用restsharp库进行http的get和post请求

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using RestSharp;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var url = "xxx";
            var client = new RestClient(url);
            var request = new RestRequest();//get提交
            request.AddHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36");
            request.AddHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            request.AddHeader("Referer", "xxx");
            var response = client.Execute(request);

            if (response.StatusCode == HttpStatusCode.OK)
            {
                //获取到返回信息后  将内容转换成自己想要的结构  
                //var result = JsonConvert.DeserializeObject<T获取保存体检返回结构>(response.Content); 
                //因为这里是公用方法不做处理,在上一级的业务类处理,这里只返回
                 Console.WriteLine(response.Content);
            }


        }

        private void button2_Click(object sender, EventArgs e)
        {
            var url = "";
            var client = new RestClient(url);
            var request = new RestRequest();
            request.Method = Method.Post;
            request.Timeout = TimeSpan.FromSeconds(5);
            //request.AddHeader("Cache-Control", "no-cache");      
            request.AddParameter("Content-Type", "text/html; charset=utf-8", ParameterType.RequestBody);

            var response = client.Execute(request);
            if (response.StatusCode == HttpStatusCode.OK)
            {
                Console.WriteLine(response.Content);
            }
    }
}

猜你喜欢

转载自blog.csdn.net/FL1623863129/article/details/143112732