go 语言请求,小案列get与post:
package main
import(
"fmt"
"net/http"
"io/ioutil"
"strings"
"os"
"io"
)
func main() {
httpGet()
content:=httpPostParmas()
savaFile(content)
}
func httpGet() {
resp,err :=http.Get("http://www.baidu.com")
if err!=nil {
fmt.Println("已经初始化")
}
defer resp.Body.Close()
body,err:=ioutil.ReadAll(resp.Body)
if err!=nil {
fmt.Println("从ioutil 获取body")
}
fmt.Println(string(body))
fmt.Println("-----------------------------------------------------------------------------------------------------------------------------------------")
}
func httpPostParmas()(content string){
client :=&http.Client{}
rep,err:=http.NewRequest("POST","http://www.baidu.com",strings.NewReader("name=cjb"))
if err!=nil{
fmt.Println("----httpRequest-------")
}
rep.Header.Set("Content-Type", "application/x-www-form-urlencoded")
rep.Header.Set("Cookie","name=anny")
resp,err:=client.Do(rep)
defer resp.Body.Close()
body ,err :=ioutil.ReadAll(resp.Body)
if err!=nil{
fmt.Println("----httpRequest----body---")
}
fmt.Println(string(body))
return string(body)
}
func savaFile(content string) {
var file *os.File
var err error
var filename string="./temp.html"
file,err=os.Create(filename)
if err!=nil{
panic(err)
}
n,err :=io.WriteString(file,content)
if err!=nil {
panic(err)
}
file.Close()
fmt.Printf("写入 %d 个字节n", n)
file.Sync()
}
有疑问加站长微信联系(非本文作者)