To request a remote web page, golang can use the method provided by the client in the net/http package to implement it. I checked some examples on the official website, but there are no comprehensive examples, so I sorted out myself:
get request
func httpGet() { resp, err := ("http:///demo/?id=1") if err != nil { // handle error } defer () body, err := () if err != nil { // handle error } (string(body)) }
Post Request
Way
func httpPost() { resp, err := ("http:///demo/", "application/x-www-form-urlencoded", ("name=cjb")) if err != nil { (err) } defer () body, err := () if err != nil { // handle error } (string(body)) }
Tips: If you use this method, the second parameter must be set to "application/x-www-form-urlencoded", otherwise the post parameter cannot be passed.
method
func httpPostForm() { resp, err := ("http:///demo/", {"key": {"Value"}, "id": {"123"}}) if err != nil { // handle error } defer () body, err := () if err != nil { // handle error } (string(body)) }
Complex requests
Sometimes you need to set header parameters, cookies and other data during requests to use the method.
func httpDo() { client := &{} req, err := ("POST", "http:///demo/", ("name=cjb")) if err != nil { // handle error } ("Content-Type", "application/x-www-form-urlencoded") ("Cookie", "name=anny") resp, err := (req) defer () body, err := () if err != nil { // handle error } (string(body)) }
For the same post request as above, the Content-Type must be set to application/x-www-form-urlencoded so that the post parameters can be passed normally.
If you want to initiate a head request, you can directly use the head method of http client. It is relatively simple, so I won't explain it here.
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.