C# Http调用详细代码
作者:猩火燎猿
本文介绍了C#中使用HttpClient类进行HTTP请求的常用方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
一、原理讲解
1. HTTP调用的基本原理
HTTP调用本质上是:
- 客户端(你的C#程序)向服务器通过网络发送HTTP请求(如GET、POST等),
- 服务器接收请求并处理,
- 然后把响应(数据、状态码等)返回给客户端。
在C#中,最常用的HTTP调用类库是 HttpClient(.NET Framework 4.5+自带),它封装了底层的Socket通信和HTTP协议细节,使开发者可以更简单地发起网络请求。
2. 主要流程
- 建立连接:
HttpClient内部通过TCP协议与目标服务器建立连接(通常通过Socket)。 - 发送请求:构造HTTP请求报文(包括请求行、请求头、请求体)。
- 等待响应:服务器返回HTTP响应报文(包括响应行、响应头、响应体)。
- 读取响应:
HttpClient读取响应内容,供程序处理。 - 关闭连接:连接可以复用(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调用内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
