如何将Delphi的TCP GET请求代码转换为C#实现?
Delphi TCP请求转C#实现方案
你的Delphi代码通过Indy组件发起带Basic认证的HTTP GET请求,读取固定185字节的响应。以下是对应的两种C#实现方式:
方式一:直接操作TCP流(与原Delphi逻辑完全对齐)
使用TcpClient模拟原代码的底层TCP操作:
using System; using System.Net.Sockets; using System.Text; class TcpRequestDemo { static void Main() { string targetHost = "192.168.52.203"; int targetPort = 80; // using语句自动释放资源,避免内存泄漏 using (TcpClient tcpClient = new TcpClient()) { tcpClient.Connect(targetHost, targetPort); if (tcpClient.Connected) { // 构造符合HTTP规范的请求字符串,\r\n对应Delphi中的CR+LF string requestContent = "GET /state.xml?noReply=0 HTTP/1.1\r\nAuthorization: Basic bm9uZTp3ZWJyZWxheQ==\r\n\r\n"; // 将字符串转为字节数组(ASCII编码与Delphi shortstring对齐) byte[] requestBytes = Encoding.ASCII.GetBytes(requestContent); using (NetworkStream stream = tcpClient.GetStream()) { // 发送请求 stream.Write(requestBytes, 0, requestBytes.Length); // 读取固定185字节的响应 byte[] responseBuffer = new byte[185]; int actualReadBytes = stream.Read(responseBuffer, 0, responseBuffer.Length); // 转换为字符串并输出 string response = Encoding.ASCII.GetString(responseBuffer, 0, actualReadBytes); Console.WriteLine(response); } } } } }
方式二:使用HttpClient(推荐,更符合HTTP规范)
如果只是发起HTTP请求,C#的HttpClient会自动处理HTTP协议细节(连接复用、响应解析等),比直接操作TCP流更简洁可靠:
using System; using System.Net.Http; using System.Net.Http.Headers; using System.Text; class HttpClientDemo { static async System.Threading.Tasks.Task Main() { using (HttpClient client = new HttpClient()) { // 设置Basic认证(原代码中的bm9uZTp3ZWJyZWxheQ==对应账号none、密码welcome) string authToken = Convert.ToBase64String(Encoding.ASCII.GetBytes("none:welcome")); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authToken); // 发送GET请求并获取响应 HttpResponseMessage response = await client.GetAsync("http://192.168.52.203/state.xml?noReply=0"); response.EnsureSuccessStatusCode(); // 确保请求成功 // 读取响应内容 string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } } }
关键说明
- 原Delphi中
Move(s[1], Buffer[0], l)的字符串转字节数组操作,C#通过Encoding.ASCII.GetBytes()直接完成 - 两种方式都用
using语句管理资源,避免手动释放的繁琐 - 若需处理复杂HTTP场景(如分块响应、重定向),优先选择
HttpClient
内容的提问来源于stack exchange,提问作者anon
相关产品推荐
相关产品推荐

