Post JSON to a RESTful service without wget, curl, netcat.

If your REST URL looks like this:

 http://some.server:8080/URI/TO/RESTful/API

1. Construct your JSON variable.

#No indentations otherwise heredoc may break.
json=$(cat <<EOF
{
       "personID": $personID,
       "firstname": "$firstname",
       "lastname": "$lastname"
}
EOF
)

2. Calculate Content-Length.

 len=${#json}

3. Open TCP socket using descriptor (3).

#exec 3<>/dev/tcp/SERVER/PORT
 exec 3<>/dev/tcp/some.server/8080

4. ECHO spoofed header to descriptor (3).

#This must be on 1 line.
 echo -e "POST /URI/TO/RESTful/API HTTP/1.1\r\nHost: some.server\r\nContent-type: application/json\r\nContent-length: $len\r\nConnection: close \r\n\r\n$json">&3
# Breaking down the header
# POST /URI/TO/RESTful/API HTTP/1.1\r\n
# Host: some.server\r\n
# Content-type: application/json\r\n
# Content-length: $len\r\n
# Connection: close \r\n\r\n
# $json

5. Show response and close descriptor (3).

 cat <&3
 exec 3<&-
comments powered by Disqus