golang post請(qǐng)求常用的幾種方式小結(jié)
更新時(shí)間:2021年04月27日 11:15:37 作者:誠寜
這篇文章主要介紹了golang post請(qǐng)求常用的幾種方式小結(jié),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
post請(qǐng)求常用的幾種方式,記錄一下
func httpPost() {
resp, err := http.Post("https://www.abcd123.top/api/v1/login",
"application/x-www-form-urlencoded",
strings.NewReader("username=test&password=ab123123"))
if err != nil {
fmt.Println(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// handle error
}
fmt.Println(string(body))
}
func httpPostForm() {
resp, err := http.PostForm("https://www.denlery.top/api/v1/login",
url.Values{"username": {"auto"}, "password": {"auto123123"}})
if err != nil {
// handle error
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// handle error
}
fmt.Println(string(body))
}
func httpPostJson() {
jsonStr :=[]byte(`{ "username": "auto", "password": "auto123123" }`)
url:= "https://www.denlery.top/api/v1/login"
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
// handle error
}
defer resp.Body.Close()
statuscode := resp.StatusCode
hea := resp.Header
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println(string(body))
fmt.Println(statuscode)
fmt.Println(hea)
}
補(bǔ)充:golang中發(fā)送post的json請(qǐng)求
看代碼吧~
package main
import (
"encoding/json"
"log"
"net/http"
)
type test_struct struct {
Test string
}
//func test(rw http.ResponseWriter, req *http.Request) {
// req.ParseForm()
// log.Println(req.Form)
// //LOG: map[{"test": "that"}:[]]
// var t test_struct
// for key, _ := range req.Form {
// log.Println(key)
// //LOG: {"test": "that"}
// err := json.Unmarshal([]byte(key), &t)
// if err != nil {
// log.Println(err.Error())
// }
// }
// log.Println(t.Test)
// //LOG: that
//}
func test(rw http.ResponseWriter, req *http.Request) {
decoder := json.NewDecoder(req.Body)
var t test_struct
err := decoder.Decode(&t)
if err != nil {
panic(err)
}
log.Println(t.Test)
}
func main() {
http.HandleFunc("/test", test)
log.Fatal(http.ListenAndServe(":8082", nil))
}

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章
Go語言實(shí)現(xiàn)定時(shí)器的原理及使用詳解
這篇文章主要為大家詳細(xì)介紹了Go語言實(shí)現(xiàn)定時(shí)器的兩種方法:一次性定時(shí)器(Timer)和周期性定時(shí)器(Ticker),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2022-12-12
GO語言gin框架實(shí)現(xiàn)管理員認(rèn)證登陸接口
這篇文章主要介紹了GO語言gin框架實(shí)現(xiàn)管理員認(rèn)證登陸接口,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-10-10

