golang的http请求

前端之家收集整理的这篇文章主要介绍了golang的http请求前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
import(
	"fmt"
	"io/IoUtil"
	"net/http"
	"net/url"
	"strings"
)

funchttpGet(){
	resp,err:=http.Get("http://www.baidu.com")
	iferr!=nil{
		//handleerror
	}

	deferresp.Body.Close()
	body,err:=IoUtil.ReadAll(resp.Body)
	iferr!=nil{
		//handleerror
	}

	fmt.Println(string(body))
}

funchttpPost(){
	resp,err:=http.Post("http://www.baidu.com","application/x-www-form-urlencoded",strings.NewReader("name=cjb"))
	iferr!=nil{
		fmt.Println(err)
	}

	deferresp.Body.Close()
	body,err:=IoUtil.ReadAll(resp.Body)
	iferr!=nil{
		//handleerror
	}

	fmt.Println(string(body))
}

funchttpPostForm(){
	resp,err:=http.PostForm("http://www.baidu.com",url.Values{"key":{"Value"},"id":{"123"}})

	iferr!=nil{
		//handleerror
	}

	deferresp.Body.Close()
	body,err:=IoUtil.ReadAll(resp.Body)
	iferr!=nil{
		//handleerror
	}

	fmt.Println(string(body))

}

funchttpDo(){
	client:=&http.Client{}

	req,err:=http.NewRequest("POST","http://www.baidu.com",strings.NewReader("name=cjb"))
	iferr!=nil{
		//handleerror
	}

	req.Header.Set("Content-Type","application/x-www-form-urlencoded")
	req.Header.Set("Cookie","name=anny")

	resp,err:=client.Do(req)

	deferresp.Body.Close()

	body,err:=IoUtil.ReadAll(resp.Body)
	iferr!=nil{
		//handleerror
	}

	fmt.Println(string(body))
}

funcmain(){
	httpGet()
	//httpPost()
	//httpPostForm()
	//httpDo()
}

复杂的请求(要设置http的header的属性等等)用httpDo方法,其它场合用get,post,postform就可以咯

golang中文网net/http包的详解:http://studygolang.com/articles/2680

原文链接:https://www.f2er.com/go/190265.html

猜你在找的Go相关文章