1.打印状态码
package main
import (
"fmt"
"net/http"
)
func main() {
url := "https://www.baidu.com/404"
response, err := http.Get(url)
if err != nil {
fmt.Println("http get error",err)
return
}
defer response.Body.Close()
fmt.Println(response.Status)
fmt.Println(response.StatusCode) //404
fmt.Println(response.Proto)
}
2.发送post请求
package main
import (
"fmt"
"net/http"
"io/ioutil"
"strings"
)
func main() {
httpPost()
//httpPostForm()
}
func httpPost() {
resp, err := http.Post("http://www.01happy.com/demo/accept.php",
"application/x-www-form-urlencoded",
strings.NewReader("name=cjb123s"))
if err != nil {
fmt.Println(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// handle error
}
fmt.Println(resp.Status)
fmt.Println(string(body))
}
/*
func httpPostForm() {
resp, err := http.PostForm("http://www.01happy.com/demo/accept.php",
url.Values{"key": {"Value"}, "id": {"123"}})
if err != nil {
// handle error
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// handle error
}
fmt.Println(string(body))
}
*/
3.添加自定义header发送get请求
package main
import (
"fmt"
"net/http"
"io/ioutil"
)
func main() {
url := "https://www.baidu.com"
httpDo(url)
}
func httpDo(url string) {
client := &http.Client{}
req, err := http.NewRequest("GET", "http://www.jd.com", nil)
if err != nil {
// handle error
}
//2种
req.Header.Add("user-agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3314.0 Safari/537.36 SE 2.X MetaSr 1.0")
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Cookie", "name=anny")
resp, err := client.Do(req)
fmt.Println(resp.Status)
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// handle error
}
err = ioutil.WriteFile("jd.html", body, 0666)
if err != nil {
fmt.Println("ioutil.WriteFile error", err)
return
}else {
fmt.Println(url, " ok")
//count <- 1
}
//fmt.Println(string(body))
}