华域联盟 Golang golang post请求常用的几种方式小结

golang post请求常用的几种方式小结

post请求常用的几种方式,记录一下

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)
}

补充:golang中发送post的json请求

看代码吧~

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))
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持华域联盟。如有错误或未考虑完全的地方,望不吝赐教。

本文由 华域联盟 原创撰写:华域联盟 » golang post请求常用的几种方式小结

转载请保留出处和原文链接:https://www.cnhackhy.com/111223.htm

本文来自网络,不代表华域联盟立场,转载请注明出处。

作者: sterben

golang在GRPC中设置client的超时时间

goland 清除所有的默认设置操作

发表回复

联系我们

联系我们

2551209778

在线咨询: QQ交谈

邮箱: [email protected]

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们