在网络编程中,HTTP(超文本传输协议)是应用最为广泛的协议之一。C#提供了强大的类库来支持HTTP通信,包括HttpClient
用于客户端请求,以及HttpListener
用于服务端监听。本文将详细介绍如何在C#中使用这些工具进行HTTP通信。
HttpClient
是.NET中用于发送HTTP请求和接收HTTP响应的类。它支持同步和异步操作,推荐使用其异步方法来避免阻塞主线程。
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);
}
}
}
cstring result = await httpClient.GetStringAsync("https://api.example.com/data");
var content = new StringContent("key=value", Encoding.UTF8, "application/x-www-form-urlencoded");
HttpResponseMessage response = await httpClient.PostAsync("https://api.example.com/data", content);
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);
}
HttpListener
是.NET中用于创建HTTP服务端的类。它提供了一个简单的方式来监听和响应HTTP请求。
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();
}
}
}
while (listener.IsListening)
{
HttpListenerContext context = await listener.GetContextAsync();
if (context.Request.Url.AbsolutePath == "/data")
{
// Handle request for /data
}
}
在服务端,安全性是一个重要的考虑因素。你应该确保:
X-Content-Type-Options
,X-Frame-Options
等。原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。