• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C#发送HTTP请求

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文内容:

  • 概述 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

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C#动态修改文件夹名称(FSO实现,不移动文件)发布时间:2022-07-13
下一篇:
使用C#选择文件夹、打开文件夹、选择文件发布时间:2022-07-13
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap