1. 程式人生 > >Golang核心程式設計(8)-net/http包的使用

Golang核心程式設計(8)-net/http包的使用

文章目錄


更多關於Golang核心程式設計知識的文章請看:Golang核心程式設計(0)-目錄頁


golang可以快速方便地實現簡單的爬蟲,本次我將使用net/http包、goquery庫,具體的使用大家可以查詢文件說明,本文只做一個簡單的介紹。最後以一個爬取CSDN的推薦文章列表的爬蟲來演示golang爬蟲的使用。

一、net/http包

net/http包是golang的內建標準庫之一,在爬蟲的應用中,它主要用於偽造請求去獲得響應,從而將其交給其他程式用以解析,主要的方法有Get()、Post()、PostFrom()和Do()。

1.1、Get請求

get請求可以直接http.Get方法

func main() {
resp, err := http.Get("http://www.baidu.com")
	if err != nil {
		// handle error
		log.Println(err)
		return
	}
	//延遲關閉resp.Body,它是一個ioReader
defer resp.Body.Close() //獲得響應頭 headers := resp.Header for k, v := range headers { fmt.Printf("k=%v, v=%v\n", k, v) } //響應狀態 fmt.Printf("resp status %s,statusCode %d\n", resp.Status, resp.StatusCode) //協議 fmt.Printf("resp Proto %s\n", resp.Proto) //響應體長度 fmt.Printf("resp content length %d\n",
resp.ContentLength) //編碼表 fmt.Printf("resp transfer encoding %v\n", resp.TransferEncoding) fmt.Printf("resp Uncompressed %t\n", resp.Uncompressed) //響應體,是主要解析的內容 fmt.Println(reflect.TypeOf(resp.Body)) // *http.gzipReader buf := bytes.NewBuffer(make([]byte, 0, 512)) length, _ := buf.ReadFrom(resp.Body) fmt.Println(len(buf.Bytes())) fmt.Println(length) fmt.Println(string(buf.Bytes())) } }

1.2、Do方法

有時需要在請求的時候設定頭引數、cookie之類的資料,就可以使用http.Do方法。

func main() {
	client := &http.Client{}

	req, err := http.NewRequest("POST", "http://www.maimaiche.com/loginRegister/login.do",
		strings.NewReader("mobile=xxxxxxxxx&isRemberPwd=1"))
	if err != nil {
		log.Println(err)
		return
	}

	req.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")

	resp, err := client.Do(req)

	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Println(err)
		return
	}

	fmt.Println(resp.Header.Get("Content-Type")) //application/json;charset=UTF-8

	type Result struct {
		Msg    string
		Status string
		Obj    string
	}

	result := &Result{}
	json.Unmarshal(body, result) //解析json字串

	if result.Status == "1" {
		fmt.Println(result.Msg)
	} else {
		fmt.Println("login error")
	}
	fmt.Println(result)
}

1.3、Post請求

如果使用http POST方法可以直接使用http.Post 或 http.PostForm


func main() {
	resp, err := http.Post("http://www.maimaiche.com/loginRegister/login.do",
		"application/x-www-form-urlencoded",
		strings.NewReader("mobile=xxxxxxxxxx&isRemberPwd=1"))
	if err != nil {
		fmt.Println(err)
		return
	}

	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println(string(body))
}

1.4、PostForm方法

用以提交表單並獲得響應

func main() {

	postParam := url.Values{
		"mobile":      {"xxxxxx"},
		"isRemberPwd": {"1"},
	}

	resp, err := http.PostForm("http://www.maimaiche.com/loginRegister/login.do", postParam)
	if err != nil {
		fmt.Println(err)
		return
	}

	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println(string(body))
}