2

Is there an easy way to make an HTTP request over an existing socket in Python?

I've seen this answer, which amounts to overriding http.client.HTTPConnection and could be adapted to my needs, but it seems to me there must be an easier way.

In my particular case, I want to make a request over an SSH channel, not a socket, but the interface is the same enough that they should be indistinguishable.

Tom
  • 7,269
  • 1
  • 42
  • 69
  • What about solving this with ssh port forwarding, in which case you wouldn't need any changes to `http.client`? – larsks Sep 26 '17 at 16:56
  • Also see https://stackoverflow.com/questions/14665064/using-python-requests-with-existing-socket-connection, which is almost a duplicate except it involves `requests` rather than `http.client`. – larsks Sep 26 '17 at 16:58
  • @larsks Yes, I've considered just doing port forwarding. However, this is part of a somewhat bigger system that already uses paramiko to open an SSH session to the server. I _could_ the set up port forwarding on that session and connect to the local port; but that would then mean I have a python thread that opens a socket that feeds another python thread that copies data into the SSH channel. It all seems a bit round-a-bout. – Tom Sep 26 '17 at 17:36

2 Answers2

1

See this answer which shows how to use the requests library over an open socket or SSH tunnel.

Tom
  • 7,269
  • 1
  • 42
  • 69
-1

You can send GET /link/to/url HTTP/1.0\n\n over the socket and read back the response. This however requires you to do any and all HTTP processing yourself, which is probably not really what you want to do. Injecting the socket into a higher level library is the better choice.

Irmen de Jong
  • 2,739
  • 1
  • 14
  • 26
  • Yes, thanks, I know how to write a raw HTTP GET request. Writing a raw multi-part POST is beyond me, though, and it seems there should be a library for that... – Tom Sep 26 '17 at 17:34