golang http請(qǐng)求(new 2019-12-02)

package main

import (
    "bytes"
    "fmt"
    "io/ioutil"
    "net/http"
    "strings"
)

func main() {
    SendXML()
}

// 普通的GET請(qǐng)求
func GetDemo1(){
    resp, _ := http.Get("http://www.baidu.com")
    data, _ := ioutil.ReadAll(resp.Body)
    fmt.Printf("response-> %s\n", data)
}


// 普通的POST請(qǐng)求
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)
}

// 自定義請(qǐng)求頭,自定義參數(shù)的GET請(qǐng)求
// 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)

    // 設(shè)置請(qǐng)求參數(shù)
    q := request.URL.Query()
    q.Add("name", "admin")
    q.Add("flag", "a")

    // 構(gòu)造請(qǐng)求參數(shù)賦值給請(qǐng)求url
    request.URL.RawQuery = q.Encode()

    // 設(shè)置請(qǐng)求頭
    // 添加請(qǐng)求頭
    request.Header.Add("cache-control", "no-cache")
    // 設(shè)置請(qǐng)求頭
    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)
}

// 自定義參數(shù)  POST請(qǐng)求
func PostDemo2(){
    payload := strings.NewReader("name=admin&password=111111")
    request, _ := http.NewRequest("POST", "http://127.0.0.1:5000/http_test", payload)

    // 設(shè)置請(qǐng)求頭
    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)
}

// 發(fā)送xml數(shù)據(jù)
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)))

    // 設(shè)置xml請(qǐng)求頭
    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)
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容