Skip to content

Instantly share code, notes, and snippets.

@amotl
Last active February 18, 2020 09:31
Show Gist options
  • Select an option

  • Save amotl/3fd7728b918d2e20e9a07904a7bf7114 to your computer and use it in GitHub Desktop.

Select an option

Save amotl/3fd7728b918d2e20e9a07904a7bf7114 to your computer and use it in GitHub Desktop.
Minimal HTTP client based on netcat
#!/bin/sh
#
# Send HTTP request with minimal dependencies, suitable to run on BusyBox.
# Requirements: "sed" and "nc" (netcat).
#
# Synopsis::
#
# microhttp POST http://john:acme@httpbin.org/post "foo=bar&baz=qux"
#
parse_url() {
# https://stackoverflow.com/questions/6174220/parse-url-in-shell-script/37750441#37750441
eval $(echo "$1" | sed -e "s#^\(\(.*\)://\)\?\(\([^:@]*\)\(:\(.*\)\)\?@\)\?\([^/?]*\)\(\(.*\)\)\?#${PREFIX:-URL_}SCHEME='\2' ${PREFIX:-URL_}USER='\4' ${PREFIX:-URL_}PASSWORD='\6' ${PREFIX:-URL_}HOST='\7' ${PREFIX:-URL_}PATH='\9'#")
}
send_request() {
HTTP_METHOD=$1
HTTP_URI=$2
HTTP_BODY=$3
PREFIX="URL_" parse_url "${HTTP_URI}"
# Compute authentication header.
[[ ! -z ${URL_USER} ]] && auth_header=$(token=$(printf "${URL_USER}:${URL_PASSWORD}" | base64); printf "Authorization: Basic $token"; printf '\\r\\n')
[[ ! -z ${HTTP_BODY} ]] && post_header="Content-Type: application/x-www-form-urlencoded\r\nContent-Length: $(printf "${HTTP_BODY}" | wc -c)\r\n"
# Build request.
request="${HTTP_METHOD} ${URL_PATH} HTTP/1.1\r\nHost: ${URL_HOST}\r\n${auth_header}${post_header}\r\n${HTTP_BODY}"
# Prepare "netcat" command.
# https://egeek.me/2014/08/17/sending-http-post-request-with-netcat/
command="nc ${URL_HOST} 80"
[[ $HTTP_METHOD = "POST" ]] && command="nc -w 1 -i 1 ${URL_HOST} 80"
# Debugging.
echo "Command: ${command}"
echo
echo ${request}
# Send request.
printf "${request}" | ${command}
}
send_request "$@"
@elektra42
Copy link
Copy Markdown

Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment