1

I need to communicate via a HTTP-Rest interface with a device. I cannot create a connection to this device actively. This device is creating a TCP-Socket with my program. So, I am listening on a port for this device. After the Socket is created, I need to send HTTP-Requests to this device on top of that socket. I Am acting as HTTP-Client and the device is acting as HTTP-Server. I cannot use WebClient for that as it creates its own TCP-Socket. But the socket as I said is already created. My fist question would be: Is there still a way to use WebClient or another alternative to create the HTTP-Requests and read out the Responses?

If I cannot use Webclient I need to implement it by myself. I saw that it is possible to use WebClient to create HTTP Header Bytes:

void SendHTTPRequest(string message)
{
  //create Header Bytes
  WebClient web = new WebClient();
  web.Headers.Set(HttpRequestHeader.Connection, "keep-alive");
  web.Headers.Set(HttpRequestHeader.Accept, "*/*");
  web.Headers.Set(HttpRequestHeader.AcceptEncoding, "gzip, deflate, br");

  //Built list with request bytes
  List<byte> bytesToSend = new List<byte>();
  bytesToSend.AddRange(Encoding.ASCII.GetBytes(message));
  bytesToSend.AddRange(web.Headers.ToByteArray());

  //Send request to the device
  WriteBytes(bytesToSend.ToArray());
}

My Second Question would be: Is there a way to decode the HTTP-Headers out of the received bytes from the response? So that I only need to implement the write and read methods for the HTTP-Body.

  • So essentially you want to separate the creation of a connection from the generating of the data necessary for sending data in HTTP format. And vice versa, for receiving responses. Just an idea, i haven't thought i through, but rather than webclient, HttpClient has associated classes which encapsulate the different parts of a request such as headers, body (in different formats) etc. So maybe those would be useful to you, to create the structure, but then you might to serialise them yourself. HttpClient is open-source .NET Core/5, so maybe take a look at how it works and the bits you need. – ADyson Feb 05 '21 at 13:22
  • See for example https://stackoverflow.com/questions/318506/converting-raw-http-request-into-httpwebrequest-object. You could probably also create your own HttpClientFactory or HttpMessageHandler; not sure if WebClient allows the same extensibility points (probably not). – CodeCaster Feb 05 '21 at 13:24

0 Answers0