C# 发送 HTTP 请求

时间:2021-08-12
本文章向大家介绍C# 发送 HTTP 请求,主要包括C# 发送 HTTP 请求使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

本文内容:

  • 概述 HTTP 请求
  • 使用 GET 方法发送请求
  • 使用 POST 方法发送请求

1、 概述

HTTP 请求通常是浏览器向服务器发送的,不过 C# 中也可以发送 HTTP 请求,本文讲解使用 C# 发送 HTTP 请求。

我这里使用的控制台(console)应用程序,其他都类似。

2、发送 GET 请求

发送请求使用 HttpClient 类,所以需要引入一下文件:

using System.Net.Http;

引入之后,初始化一个 HttpClient 类,HttpClient 类有一个 GetStringAsync 方法可以发送 GET 请求,参数为目标地址(URL)。

namespace testdemo
{
    class Program
    {
        private static readonly HttpClient client = new HttpClient();
  
        public  static  void Main()
        {
            Program.get();  
        }

        public static async void get(){
            var responseString = await client.GetStringAsync("http://127.0.0.1:23/api");
            Console.WriteLine(responseString);
        }
    }
  
}

使用抓包工具分析,发送的 HTTP 请求的格式如下:

GET /api HTTP/1.1
Host: 127.0.0.1:23

3、发送 POST 请求

发送 post 请求也大致相似,我们要使用 PostAsync 方法。

using System.Collections.Generic;

namespace testdemo
{
    class Program
    {
        private static readonly HttpClient client = new HttpClient();
  
        public  static  void Main()
        {
            Program.post();
	    Console.Read();
        }

        public static async void post(){
            // 创建一个字典,添加数据
            Dictionary<string, string> values = new Dictionary<string, string>();
            values.Add("name", "hello");
            values.Add("age", "12");

            // 数据转化为 key=val 格式
            var content = new FormUrlEncodedContent(values);

            // 发送请求
            var response = await client.PostAsync("http://127.0.0.1:23", content);
            // 获取数据
            var responseString = await response.Content.ReadAsStringAsync();
            Console.WriteLine(responseString);
        }
    }
  
}

发送的 HTTP 请求的格式如下:

POST / HTTP/1.1
Host: 127.0.0.1:23
Content-Type: application/x-www-form-urlencoded
Content-Length: 17

name=hello&age=12

原文地址:https://www.cnblogs.com/gegecode/p/15131829.html