简体   繁体   中英

return raw binary ipv4 GET repsonse in elixir

I'm aware of the existence of libraries that return HTTP responses as struct s:

> HTTPoison.get!("http://httpbin.org/get")
> %HTTPoison.Response{body: "{\n  \"args\": {}, \n  \"headers\": {\n   \"Host\": \"httpbin.org\", \n    \"User-Agent\": \"hackney/1.6.6\"\n  }, \n  \"origin\": \"86.30.176.31\", \n  \"url\": \"http://httpbin.org/get\"\n}\n", headers: [{"Server", "nginx"}, {"Date", "Sun, 12 Mar 2017 06:05:29 GMT"},{"Content-Type", "application/json"}, {"Content-Length", "165"}, {"Connection", "keep-alive"}, {"Access-Control-Allow-Origin", "*"}, {"Access-Control-Allow-Credentials", "true"}], status_code: 200}

However how do I get the raw binary form of a ipv4 HTTP response packet in elixir?

As per Dogbert's suggestion, I tried using gen_tcp , but got the following:

iex(1)> {:ok, port} = :gen_tcp.connect('httpbin.org',80,[:binary, active: 
false, packet: :http])
{:ok, #Port<0.6531>}
iex(2)> :gen_tcp.send(port, "GET /get HTTP/1.1\r\nHost: httpbin.org\r\n")
:ok
iex(3)> :gen_tcp.recv(port,0)
{:error, :closed}

What am I doing wrong here?

Getting rid of the packet: :http option in gen_tcp.connect and adding another \\r\\n at the end of the HTTP text solved it:

iex(3)> {:ok, packet_binary} = :gen_tcp.recv(port,0)
{:ok, {:http_response, {1, 1}, 200, 'OK'}}

iex(4)> {:ok, port} = :gen_tcp.connect('httpbin.org',80,[:binary, active: false])               
{:ok, #Port<0.6706>}

iex(5)> :gen_tcp.send(port, "GET /get HTTP/1.1\r\nHost: httpbin.org\r\n\r\n")    
:ok

iex(6)> {:ok, packet_binary} = :gen_tcp.recv(port,0)                             
{:ok,
 "HTTP/1.1 200 OK\r\nServer: nginx\r\nDate: Sun, 12 Mar 2017 14:01:05 GMT\r\nContent-Type: application/json\r\nContent-Length: 129\r\nConnection: keep-alive\r\nAccess-Control-Allow-Origin: *\r\nAccess-Control-Allow-Credentials: true\r\n\r\n{\n  \"args\": {}, \n  \"headers\": {\n    \"Host\": \"httpbin.org\"\n  }, \n  \"origin\": \"86.30.176.31\", \n  \"url\": \"http://httpbin.org/get\"\n}\n"}

iex(7)> IO.puts(packet_binary)  
HTTP/1.1 200 OK
Server: nginx
Date: Sun, 12 Mar 2017 14:01:05 GMT
Content-Type: application/json
Content-Length: 129
Connection: keep-alive
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true

{
  "args": {}, 
  "headers": {
    "Host": "httpbin.org"
  }, 
  "origin": "86.30.176.31", 
  "url": "http://httpbin.org/get"
}

:ok

iex(8)> is_binary(packet_binary)
true

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