1. Web client
This is a handy way to test your web services (with the GET verb).
For more advanced examples using other verbs or data streaming, basic auth, etc see: https://crystal-lang.org/api/0.32.1/HTTP/Client.html
code/crystal/src/web_server/web_client.cr
require "http/client"
response = HTTP::Client.get "http://localhost:8080"
puts response.status_code
# lines as an iterator -- faster for large pages and processing
response.body.each_line{ |line| puts line }
# iterating through collection of lines (also valid)
response.body.lines.each{ |line| puts line }
# normally default is html
response = HTTP::Client.get "http://localhost:8080/bill/tihen"
puts response.status_code
response.body.each_line{ |line| puts line }
response = HTTP::Client.get "http://localhost:8080/bill/tihen.json"
puts response.status_code
response.body.each_line{ |line| puts line }
response = HTTP::Client.get "http://localhost:8080/bill/tihen.text"
puts response.status_code
response.body.each_line{ |line| puts line }
# send params: # => dog=Nyima&cat=Shiné
params = HTTP::Params.encode({"dog" => "Nyima", "cat" => "Shiné"})
response = HTTP::Client.get "http://localhost:8080/bill/tihen.txt?" + params
puts response.status_code
response.body.each_line{ |line| puts line }
params = HTTP::Params.encode({"dog" => "Nyima", "cat" => "Shiné"})
response = HTTP::Client.get "http://localhost:8080/bill/tihen.text?" + params
puts response.status_code
response.body.each_line{ |line| puts line }
params = HTTP::Params.encode({"dog" => "Nyima", "cat" => "Shiné"})
response = HTTP::Client.get "http://localhost:8080/bill/tihen.json?" + params
puts response.status_code
response.body.each_line{ |line| puts line }
params = HTTP::Params.encode({"dog" => "Nyima", "cat" => "Shiné"})
response = HTTP::Client.get "http://localhost:8080/bill/tihen.html?" + params
puts response.status_code
response.body.each_line{ |line| puts line }
In this case its easier to see generate a variety of web packets with out own client.
Run with:
$ crystal code/crystal/src/web_server/web_client.cr
Note
|
one helpful feature is that the http client automatically encodes any non-ascii characters into safe ascii characters! You will see if send the param Shiné it will arrive at the server automatically as Shin%C3%A9 - without you having to do anything more!
|