简体   繁体   中英

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.

I tried to use HTTPClient, but it didnt work since i need to construct a HTTPRequestMessage before call the Send method.

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.

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.

This is extremely unusual. HttpClient can't be used for this, unless you know of a parser for 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 . And you'll need to do your own TLS negotiation - SslStream may help there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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