C# Http调用详细代码

 更新时间:2025年11月17日 10:55:48   作者:猩火燎猿  
本文介绍了C#中使用HttpClient类进行HTTP请求的常用方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

一、原理讲解

1. HTTP调用的基本原理

HTTP调用本质上是:

  • 客户端(你的C#程序)向服务器通过网络发送HTTP请求(如GET、POST等),
  • 服务器接收请求并处理,
  • 然后把响应(数据、状态码等)返回给客户端。

在C#中,最常用的HTTP调用类库是 HttpClient(.NET Framework 4.5+自带),它封装了底层的Socket通信和HTTP协议细节,使开发者可以更简单地发起网络请求。

2. 主要流程

  1. 建立连接HttpClient内部通过TCP协议与目标服务器建立连接(通常通过Socket)。
  2. 发送请求:构造HTTP请求报文(包括请求行、请求头、请求体)。
  3. 等待响应:服务器返回HTTP响应报文(包括响应行、响应头、响应体)。
  4. 读取响应HttpClient读取响应内容,供程序处理。
  5. 关闭连接:连接可以复用(Keep-Alive),也可关闭。

3. 底层原理简述

  • HttpClient基于HttpWebRequest/HttpWebResponse(.NET Core和.NET 5+底层有优化)。
  • 网络通信实际是通过Socket进行数据收发。
  • HTTP协议规定了请求和响应的格式,HttpClient负责封装和解析。

4. 代码示例与报文结构

以GET请求为例:

代码

using System;
using System.Net.Http;
using System.Threading.Tasks;
 
class Program
{
    public static async Task Main(string[] args)
    {
        using (HttpClient client = new HttpClient())
        {
            HttpResponseMessage response = await client.GetAsync("https://jsonplaceholder.typicode.com/posts/1");
            string content = await response.Content.ReadAsStringAsync();
            Console.WriteLine(content);
        }
    }
}

实际HTTP报文

请求报文:

GET /posts/1 HTTP/1.1
Host: jsonplaceholder.typicode.com
User-Agent: ...
Accept: ...
Connection: keep-alive
...

响应报文:

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 292
...

{
  "userId": 1,
  "id": 1,
  "title": "...",
  "body": "..."
}

5. 关键点

  • 请求方式:决定HTTP请求的类型(GET/POST/PUT/DELETE等)。
  • 请求头/响应头:包含元数据(如Content-Type、Authorization等)。
  • 请求体/响应体:实际传输的数据(如JSON、文本、文件等)。
  • 状态码:服务器响应的处理结果(如200、404、500等)。

6. 总结

  • C#通过HttpClient等类库,底层用Socket实现HTTP协议的数据收发。
  • HttpClient负责封装HTTP报文,简化开发流程。
  • HTTP调用的本质是:构造请求 → 发送 → 等待响应 → 解析响应

二、完整代码示例

1. 引入命名空间

using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

2. GET请求

public static async Task HttpGetAsync()
{
    using (HttpClient client = new HttpClient())
    {
        // 设置请求头(可选)
        client.DefaultRequestHeaders.Add("User-Agent", "C# App");
 
        // 发送GET请求
        HttpResponseMessage response = await client.GetAsync("https://jsonplaceholder.typicode.com/posts/1");
 
        // 判断是否成功
        if (response.IsSuccessStatusCode)
        {
            string content = await response.Content.ReadAsStringAsync();
            Console.WriteLine("GET请求结果:");
            Console.WriteLine(content);
        }
        else
        {
            Console.WriteLine($"GET请求失败,状态码:{response.StatusCode}");
        }
    }
}

3. POST请求(发送JSON)

public static async Task HttpPostAsync()
{
    using (HttpClient client = new HttpClient())
    {
        // 构造要发送的数据
        string json = "{\"title\": \"foo\", \"body\": \"bar\", \"userId\": 1}";
        StringContent content = new StringContent(json, Encoding.UTF8, "application/json");
 
        // 发送POST请求
        HttpResponseMessage response = await client.PostAsync("https://jsonplaceholder.typicode.com/posts", content);
 
        // 判断是否成功
        if (response.IsSuccessStatusCode)
        {
            string result = await response.Content.ReadAsStringAsync();
            Console.WriteLine("POST请求结果:");
            Console.WriteLine(result);
        }
        else
        {
            Console.WriteLine($"POST请求失败,状态码:{response.StatusCode}");
        }
    }
}

4. 主函数调用示例

public static async Task Main(string[] args)
{
    await HttpGetAsync();
    await HttpPostAsync();
}

5. 完整代码示例

using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
 
class Program
{
    public static async Task HttpGetAsync()
    {
        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("User-Agent", "C# App");
            HttpResponseMessage response = await client.GetAsync("https://jsonplaceholder.typicode.com/posts/1");
            if (response.IsSuccessStatusCode)
            {
                string content = await response.Content.ReadAsStringAsync();
                Console.WriteLine("GET请求结果:");
                Console.WriteLine(content);
            }
            else
            {
                Console.WriteLine($"GET请求失败,状态码:{response.StatusCode}");
            }
        }
    }
 
    public static async Task HttpPostAsync()
    {
        using (HttpClient client = new HttpClient())
        {
            string json = "{\"title\": \"foo\", \"body\": \"bar\", \"userId\": 1}";
            StringContent content = new StringContent(json, Encoding.UTF8, "application/json");
            HttpResponseMessage response = await client.PostAsync("https://jsonplaceholder.typicode.com/posts", content);
            if (response.IsSuccessStatusCode)
            {
                string result = await response.Content.ReadAsStringAsync();
                Console.WriteLine("POST请求结果:");
                Console.WriteLine(result);
            }
            else
            {
                Console.WriteLine($"POST请求失败,状态码:{response.StatusCode}");
            }
        }
    }
 
    public static async Task Main(string[] args)
    {
        await HttpGetAsync();
        await HttpPostAsync();
    }
}

6. 添加自定义请求头(如Token)

public static async Task HttpGetWithTokenAsync()
{
    using (HttpClient client = new HttpClient())
    {
        // 添加Bearer Token
        client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "your_token_here");
        
        HttpResponseMessage response = await client.GetAsync("https://api.example.com/data");
        string result = await response.Content.ReadAsStringAsync();
        Console.WriteLine(result);
    }
}

7. 发送表单数据(application/x-www-form-urlencoded)

public static async Task HttpPostFormAsync()
{
    using (HttpClient client = new HttpClient())
    {
        var formData = new FormUrlEncodedContent(new[]
        {
            new KeyValuePair<string, string>("username", "test"),
            new KeyValuePair<string, string>("password", "123456")
        });
 
        HttpResponseMessage response = await client.PostAsync("https://httpbin.org/post", formData);
        string result = await response.Content.ReadAsStringAsync();
        Console.WriteLine(result);
    }
}

8. 上传文件(multipart/form-data)

public static async Task HttpPostFileAsync()
{
    using (HttpClient client = new HttpClient())
    {
        using (var multipartFormContent = new MultipartFormDataContent())
        {
            // 添加文件
            var fileStream = System.IO.File.OpenRead("test.txt");
            multipartFormContent.Add(new StreamContent(fileStream), name: "file", fileName: "test.txt");
 
            // 添加其他表单字段
            multipartFormContent.Add(new StringContent("value1"), "field1");
 
            HttpResponseMessage response = await client.PostAsync("https://httpbin.org/post", multipartFormContent);
            string result = await response.Content.ReadAsStringAsync();
            Console.WriteLine(result);
        }
    }
}

9. 设置超时和异常处理

public static async Task HttpGetWithTimeoutAsync()
{
    using (HttpClient client = new HttpClient())
    {
        client.Timeout = TimeSpan.FromSeconds(5); // 设置超时时间
 
        try
        {
            HttpResponseMessage response = await client.GetAsync("https://jsonplaceholder.typicode.com/posts/1");
            string content = await response.Content.ReadAsStringAsync();
            Console.WriteLine(content);
        }
        catch (TaskCanceledException ex)
        {
            Console.WriteLine("请求超时: " + ex.Message);
        }
        catch (Exception ex)
        {
            Console.WriteLine("请求异常: " + ex.Message);
        }
    }
}

10. 反序列化JSON响应为对象

你可以使用 System.Text.Json 或 Newtonsoft.Json,这里用自带的 System.Text.Json

using System.Text.Json;
 
public class Post
{
    public int userId { get; set; }
    public int id { get; set; }
    public string title { get; set; }
    public string body { get; set; }
}
 
public static async Task HttpGetDeserializeAsync()
{
    using (HttpClient client = new HttpClient())
    {
        HttpResponseMessage response = await client.GetAsync("https://jsonplaceholder.typicode.com/posts/1");
        string content = await response.Content.ReadAsStringAsync();
 
        // 反序列化为对象
        var post = JsonSerializer.Deserialize<Post>(content);
        Console.WriteLine($"标题: {post.title}, 内容: {post.body}");
    }
}

到此这篇关于C# Http调用详细代码的文章就介绍到这了,更多相关C# Http调用内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • SQLite之C#版 System.Data.SQLite使用方法

    SQLite之C#版 System.Data.SQLite使用方法

    这篇文章主要介绍了SQLite之C#版 System.Data.SQLite使用方法,需要的朋友可以参考下
    2020-10-10
  • C# Helper开发一个简单的端口监控工具

    C# Helper开发一个简单的端口监控工具

    C# 端口监控 Helper 是一款基于C#语言的工具,这个意义在于帮助开发者快速实现对指定端口的监控,以保障(观察)网络服务的正常运行,下面我们就来看看具体实现方法吧
    2025-09-09
  • C#实现图片放大功能的按照像素放大图像方法

    C#实现图片放大功能的按照像素放大图像方法

    这篇文章主要介绍了C#实现图片放大功能的按照像素放大图像方法,功能非常实用,需要的朋友可以参考下
    2014-07-07
  • Unity控制指针旋转到指定位置

    Unity控制指针旋转到指定位置

    这篇文章主要为大家详细介绍了Unity控制指针旋转到指定位置,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-02-02
  • Unity游戏开发之炸弹人游戏的实现

    Unity游戏开发之炸弹人游戏的实现

    大家小时候肯定玩过这款游戏,炸弹人也算是经典中的经典啦。本文将利用Unity模拟实现这一经典游戏,感兴趣的小伙伴可以跟随小编一起学习一下
    2022-03-03
  • C#通过NPOI操作Excel的实例代码

    C#通过NPOI操作Excel的实例代码

    C#操作Excel的方法有很多种,本文介绍了C#通过NPOI操作Excel,具有一定的参考价值,有兴趣的可以了解一下。
    2017-01-01
  • C#模拟Http与Https请求框架类实例

    C#模拟Http与Https请求框架类实例

    这篇文章主要介绍了C#模拟Http与Https请求框架类,实例分析了处理http与https请求的方法与信息处理的技巧,需要的朋友可以参考下
    2014-12-12
  • C#使用protobuf-net进行序列化的详细操作

    C#使用protobuf-net进行序列化的详细操作

    本文带领大家学习C#中protobuf-net工具的另一种使用体验,这个工具的使用体验属于Code-First模式,先定义类型,并使用注解进行标记,不需要先编写.proto文件,感兴趣的朋友跟随小编一起看看吧
    2021-11-11
  • 使用C#实现解析Excel公式

    使用C#实现解析Excel公式

    在日常工作中,我们经常需要在Excel中使用公式对表中数据进行计算和分析,所以本文小编主要来和大家介绍一下如何在C#中实现解析Excel公式,感兴趣的可以了解下
    2024-02-02
  • C# 实现简易的串口监视上位机功能附源码下载

    C# 实现简易的串口监视上位机功能附源码下载

    这篇文章主要介绍了C# 实现简易的串口监视上位机功能,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-11-11

最新评论