C#的HTTP 客户端和服务

2024-10-09 21:57:05 浏览数 (1)

在网络编程中,HTTP(超文本传输协议)是应用最为广泛的协议之一。C#提供了强大的类库来支持HTTP通信,包括HttpClient用于客户端请求,以及HttpListener用于服务端监听。本文将详细介绍如何在C#中使用这些工具进行HTTP通信。

HTTP客户端:HttpClient

HttpClient是.NET中用于发送HTTP请求和接收HTTP响应的类。它支持同步和异步操作,推荐使用其异步方法来避免阻塞主线程。

创建HttpClient实例

代码语言:javascript复制
using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("https://api.example.com");
            HttpResponseMessage response = await client.GetAsync("/data");
            response.EnsureSuccessStatusCode();
            string responseBody = await response.Content.ReadAsStringAsync();
            Console.WriteLine(responseBody);
        }
    }
}

发送GET请求

代码语言:javascript复制
cstring result = await httpClient.GetStringAsync("https://api.example.com/data");

发送POST请求

代码语言:javascript复制
var content = new StringContent("key=value", Encoding.UTF8, "application/x-www-form-urlencoded");
HttpResponseMessage response = await httpClient.PostAsync("https://api.example.com/data", content);

错误处理

代码语言:javascript复制
try
{
    HttpResponseMessage response = await httpClient.GetAsync("https://api.example.com/data");
    response.EnsureSuccessStatusCode();
    string responseBody = await response.Content.ReadAsStringAsync();
}
catch (HttpRequestException e)
{
    Console.WriteLine("nException Caught!");
    Console.WriteLine("Message :{0} ", e.Message);
}

HTTP服务端:HttpListener

HttpListener是.NET中用于创建HTTP服务端的类。它提供了一个简单的方式来监听和响应HTTP请求。

创建和启动服务端

代码语言:javascript复制
using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        HttpListener listener = new HttpListener();
        listener.Prefixes.Add("http://localhost:8080/");
        listener.Start();
        Console.WriteLine("Listening...");

        while (true)
        {
            HttpListenerContext context = await listener.GetContextAsync();
            HttpListenerRequest request = context.Request;
            HttpListenerResponse response = context.Response;

            string responseString = "Hello, world!";
            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);

            response.ContentLength64 = buffer.Length;
            Stream output = response.OutputStream;
            output.Write(buffer, 0, buffer.Length);
            // You must close the output stream.
            output.Close();
        }
    }
}

处理请求

代码语言:javascript复制
while (listener.IsListening)
{
    HttpListenerContext context = await listener.GetContextAsync();
    if (context.Request.Url.AbsolutePath == "/data")
    {
        // Handle request for /data
    }
}

安全性

在服务端,安全性是一个重要的考虑因素。你应该确保:

  • 验证所有输入数据。
  • 使用HTTPS来加密传输的数据。
  • 设置适当的HTTP响应头,如X-Content-Type-OptionsX-Frame-Options等。

0 人点赞