[Golang]Http get和post请求示例
发布时间:2020-12-16 18:39:55 所属栏目:大数据 来源:网络整理
导读:golang要请求远程网页,可以使用net/http包中的client提供的方法实现。查看了官方网站有一些示例,没有太全面的例子,于是自己整理了一下。 get请求 get请求可以直接http.Get方法,非常简单。 func httpGet () { resp , err := http . Get ( "http://www.01h
golang要请求远程网页,可以使用net/http包中的client提供的方法实现。查看了官方网站有一些示例,没有太全面的例子,于是自己整理了一下。 get请求get请求可以直接http.Get方法,非常简单。 func httpGet() { resp, err := http.Get("http://www.01happy.com/demo/accept.php?id=1") if err != nil { // handle error } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) nil { // handle error } fmt.Println(string(body)) } post请求一种是使用http.Post方式func httpPost() { resp,175);">Post("http://www.01happy.com/demo/accept.php", "application/x-www-form-urlencoded", strings.NewReader("name=cjb")) nil { fmt.Println(err) } defer resp.string(body)) } Tips:使用这个方法的话,第二个参数要设置成”application/x-www-form-urlencoded”,否则post参数无法传递。 一种是使用http.PostForm方法func httpPostForm() { resp,175);">PostForm( url.Values{"key": {"Value"},0);">"id": {"123"}}) 复杂的请求 |