package main
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"strings"
)
func main() {
SendXML()
}
// 普通的GET请求
func GetDemo1(){
resp, _ := http.Get("http://www.baidu.com")
data, _ := ioutil.ReadAll(resp.Body)
fmt.Printf("response-> %s\n", data)
}
// 普通的POST请求
func PostDemo1(){
resp, _ := http.Post("http://127.0.0.1:5000/http_test", "application/json", nil)
data, _ := ioutil.ReadAll(resp.Body)
fmt.Printf("response-> %s\n", data)
}
// 自定义请求头,自定义参数的GET请求
// http://127.0.0.1:5000/http_test?flag=a&name=admin
func GetDemo2(){
request, _ := http.NewRequest("GET", "http://127.0.0.1:5000/http_test", nil)
// 设置请求参数
q := request.URL.Query()
q.Add("name", "admin")
q.Add("flag", "a")
// 构造请求参数赋值给请求url
request.URL.RawQuery = q.Encode()
// 设置请求头
// 添加请求头
request.Header.Add("cache-control", "no-cache")
// 设置请求头
request.Header.Set("content-type", "application/x-www-form-urlencoded")
resp, _ := http.DefaultClient.Do(request)
data, _ := ioutil.ReadAll(resp.Body)
defer resp.Body.Close()
fmt.Printf("%s\n", data)
}
// 自定义参数 POST请求
func PostDemo2(){
payload := strings.NewReader("name=admin&password=111111")
request, _ := http.NewRequest("POST", "http://127.0.0.1:5000/http_test", payload)
// 设置请求头
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, _ := http.DefaultClient.Do(request)
data, _ := ioutil.ReadAll(resp.Body)
defer resp.Body.Close()
fmt.Printf("%s\n", data)
}
// 发送xml数据
func SendXML(){
xml_str := `
<?xml version="1.0" encoding="UTF-8"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>`
request, _ := http.NewRequest("POST", "http://127.0.0.1:5000/http_test", bytes.NewBuffer([]byte(xml_str)))
// 设置xml请求头
request.Header.Set("Content-Type", "text/html;charset:utf-8;")
resp, _ := http.DefaultClient.Do(request)
data, _ := ioutil.ReadAll(resp.Body)
defer resp.Body.Close()
fmt.Printf("%s\n", data)
}
golang http请求(new 2019-12-02)
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- get 与 post 提交方法的区别? 除此之外你还知道其它的 HTTP 请求吗 get 是把参数数据队列加到提交...
- c.readRequest(ctx)读请求 先配置Header最长读取时间、req最长读取时间、req最大读取长度...
- 转stackoverflow一段话:https://stackoverflow.com/questions/185...
- 对Golang HTTP标准库进行了封装,提供了更易用优雅的API,类似于Python-requests之于Pyt...