简体   繁体   English

如何在 C# 中发送原始 HTTP 请求?

[英]How can I send a raw HTTP request in C#?

I am writing a .NET 5 application which sends requests over a TLS connection to some endpoint.我正在编写一个 .NET 5 应用程序,它通过 TLS 连接向某个端点发送请求。

I tried to use HTTPClient, but it didnt work since i need to construct a HTTPRequestMessage before call the Send method.我尝试使用 HTTPClient,但它不起作用,因为我需要在调用 Send 方法之前构造一个 HTTPRequestMessage。

HttpClient client = new HttpClient();
var response = await client.SendAsync(requestMessage);

var responseContent = await response.Content.ReadAsStringAsync();

I need to send the bytes of pre-serialized request above without converting it to an HTTP object.我需要发送上面预序列化请求的字节而不将其转换为 HTTP object。

POST /app/test HTTP/1.1
Content-type: application/json
Content-Length: 23

{"msg": "test message"}

I need to send the bytes of pre-serialized request above without converting it to an HTTP object.我需要发送上面预序列化请求的字节而不将其转换为 HTTP object。

This is extremely unusual.这是非常不寻常的。 HttpClient can't be used for this, unless you know of a parser for HttpRequestMessage . HttpClient不能用于此,除非您知道HttpRequestMessage的解析器。 There may be a library out there that does that, but I don't know of one.可能有一个图书馆可以做到这一点,但我不知道有哪一个。

To send a byte array, you'd have to use a lower-level connection like Socket or TcpClient .要发送字节数组,您必须使用较低级别的连接,如SocketTcpClient And you'll need to do your own TLS negotiation - SslStream may help there.而且您需要进行自己的 TLS 协商 - SslStream可能会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM