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 mainimport ('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_structerr := decoder.Decode(&t)if err != nil {panic(err)}log.Println(t.Test)}func main() {http.HandleFunc('/test', test)log.Fatal(http.ListenAndServe(':8082', nil))}
以上为个人经验,希望能给大家一个参考,也希望大家多多支持优爱好网。如有错误或未考虑完全的地方,望不吝赐教。
相关文章:
1. 怎么让div+css兼容ie6ie7ie8ie9和FireFoxChrome等浏览器2. requestAnimationFrame使用示例详解3. 基于JavaScript实现图片裁剪功能4. React优雅的封装SvgIcon组件示例5. uniapp自定义验证码输入框并隐藏光标6. 详解JavaScript中原始数据类型Symbol的使用7. JavaScript深拷贝方法structuredClone使用8. uniapp 手机验证码输入框实现代码(随机数、倒计时、隐藏手机号码中间四位)可以直接使用9. 使用Node.js实现Clean Architecture方法示例详解10. Jquery使用原生AJAX方法请求数据