Golang HTTP GET POST请求

package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
    "os"
    "strings"
)

func GET() {
    client := &http.Client{}
    reqest, err := http.NewRequest("GET", "http://www.baidu.com/", nil) //建立一个请求
    if err != nil {
        fmt.Println("Fatal error ", err.Error())
        os.Exit(0)
    }
    //Add 头协议
    reqest.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
    reqest.Header.Add("Accept-Language", "ja,zh-CN;q=0.8,zh;q=0.6")
    reqest.Header.Add("Connection", "keep-alive")
    reqest.Header.Add("Cookie", "设置cookie")
    reqest.Header.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0")
    response, err := client.Do(reqest) //提交
    defer response.Body.Close()
    cookies := response.Cookies() //遍历cookies
    for _, cookie := range cookies {
        fmt.Println("cookie:", cookie)
    }

    body, err1 := ioutil.ReadAll(response.Body)
    if err1 != nil {
        // handle error
    }
    fmt.Println(string(body)) //网页源码

}

func post() {
    client := &http.Client{}
    req, err := http.NewRequest("POST", "http://xxxxx", strings.NewReader("name=1&age=2"))
    if err != nil {
        // handle error
    }

    reqest.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
    reqest.Header.Add("Accept-Language", "ja,zh-CN;q=0.8,zh;q=0.6")
    reqest.Header.Add("Connection", "keep-alive")
    reqest.Header.Add("Cookie", "设置cookie")
    reqest.Header.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0")
    resp, err := client.Do(req)
    cookies := resp.Cookies()
    for _, cookie := range cookies {
        fmt.Println("cookie:", cookie)
    }
    defer resp.Body.Close()

    _, err1 := ioutil.ReadAll(resp.Body)
    if err1 != nil {
        // handle error
    }

    fmt.Println(string(body))
}
func main() {
    GET()
}

 

本文来自:博客园

感谢作者:dq4402935

查看原文:Golang HTTP GET POST请求

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。