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)
}
有疑问加站长微信联系(非本文作者)