设为首页 加入收藏

TOP

golang常用的http请求操作(二)
2019-08-14 00:08:36 】 浏览:152
Tags:golang 常用 http 请求 操作
"net/http" "net/url" ) func main() { urlValues := url.Values{} urlValues.Add("name","zhaofan") urlValues.Add("age","22") resp, _ := http.PostForm("http://httpbin.org/post",urlValues) body, _ := ioutil.ReadAll(resp.Body) fmt.Println(string(body)) }

结果如下:

{
  "args": {}, 
  "data": "", 
  "files": {}, 
  "form": {
    "age": "22", 
    "name": "zhaofan"
  }, 
  "headers": {
    "Accept-Encoding": "gzip", 
    "Content-Length": "19", 
    "Content-Type": "application/x-www-form-urlencoded", 
    "Host": "httpbin.org", 
    "User-Agent": "Go-http-client/1.1"
  }, 
  "json": null, 
  "origin": "211.138.20.170, 211.138.20.170", 
  "url": "https://httpbin.org/post"
}

另外一种方式

package main

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

func main() {
    urlValues := url.Values{
        "name":{"zhaofan"},
        "age":{"23"},
    }
    reqBody:= urlValues.Encode()
    resp, _ := http.Post("http://httpbin.org/post", "text/html",strings.NewReader(reqBody))
    body,_:= ioutil.ReadAll(resp.Body)
    fmt.Println(string(body))
}

结果如下:

{
  "args": {}, 
  "data": "age=23&name=zhaofan", 
  "files": {}, 
  "form": {}, 
  "headers": {
    "Accept-Encoding": "gzip", 
    "Content-Length": "19", 
    "Content-Type": "text/html", 
    "Host": "httpbin.org", 
    "User-Agent": "Go-http-client/1.1"
  }, 
  "json": null, 
  "origin": "211.138.20.170, 211.138.20.170", 
  "url": "https://httpbin.org/post"
}

发送JSON数据的post请求

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
)

func main() {
    client := &http.Client{}
    data := make(map[string]interface{})
    data["name"] = "zhaofan"
    data["age"] = "23"
    bytesData, _ := json.Marshal(data)
    req, _ := http.NewRequest("POST","http://httpbin.org/post",bytes.NewReader(bytesData))
    resp, _ := client.Do(req)
    body, _ := ioutil.ReadAll(resp.Body)
    fmt.Println(string(body))

}

结果如下:

{
  "args": {}, 
  "data": "{\"age\":\"23\",\"name\":\"zhaofan\"}", 
  "files": {}, 
  "form": {}, 
  "headers": {
    "Accept-Encoding": "gzip", 
    "Content-Length": "29", 
    "Host": "httpbin.org", 
    "User-Agent": "Go-http-client/1.1"
  }, 
  "json": {
    "age": "23", 
    "name": "zhaofan"
  }, 
  "origin": "2
首页 上一页 1 2 3 下一页 尾页 2/3/3
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇深度解密Go语言之关于 interface .. 下一篇2.GO-可变参数函数、匿名函数和函..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目