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...