用curl可以访问的地址内容,如何通过go语言的http包实现

比如我在命令行实现

 curl --data '{"jsonrpc":"1.0","id":"curltest","method":"getwalletinfo","params":[]}' http://user:123456@127.0.0.1:18332/

返回内容如

 {"result":{"walletname":"","walletversion":169900,"balance":0.00652964,"unconfirmed_balance":0.00000000,"immature_balance":0.00000000,"txcount":9,"keypoololdest":1541586836,"keypoolsize":1000,"keypoolsize_hd_internal":1000,"paytxfee":0.00000000,"hdseedid":"903b49b210bd3ef7e36326b34acdadff831ea1e0","hdmasterkeyid":"903b49b210bd3ef7e36326b34acdadff831ea1e0","private_keys_enabled":true},"error":null,"id":"curltest"}

我如何通过go语言来返回相同的内容?http.post函数能否完成,如果能完成需要怎么做?

2个回答

curl 的--data就是POST的json数据给服务器。所以你go也是提交对应的post请求和数据就可以了

func main() {
    url := "http://restapi3.apiary.io/notes"
    fmt.Println("URL:>", url)

    var jsonStr = []byte(`{"title":"Buy cheese and bread for breakfast."}`)
    req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
    req.Header.Set("X-Custom-Header", "myvalue")
    req.Header.Set("Content-Type", "application/json")

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    fmt.Println("response Status:", resp.Status)
    fmt.Println("response Headers:", resp.Header)
    body, _ := ioutil.ReadAll(resp.Body)
    fmt.Println("response Body:", string(body))
} 
weixin_42654444
昨夜是今晨的开始 str := strings.Fields(s) url := "http://userto123456@127.0.0.1:8332" curl1 := {"jsonrpc":"1.0","id":"curltest","method":" curl2 := ","params":[ curl3 := ]} var quest string switch len(str) { case 1: quest = fmt.Sprintln(curl1 + str[0] + curl2 + curl3) case 2: quest = fmt.Sprintln(curl1 + str[0] + curl2 + str[1] + curl3) } var jsonStr = []byte(quest) req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr)) req.Header.Set("X-Custom-Header", "myvalue") req.Header.Set("Content-Type", "application/json") //req.Close = true client := &http.Client{ //Transport: &http.Transport{ //Dial:func(netw, addr string) (net.Conn, error) { // conn, err := net.DialTimeout(netw, addr, time.Second*2) //设置建立连接超时 // if err != nil { // return nil, err // } // conn.SetDeadline(time.Now().Add(time.Second * 2)) //设置发送接受数据超时 // return conn, nil //}, //ResponseHeaderTimeout: time.Second * 2, //}, } resp, err := client.Do(req) if err != nil { panic(err) } defer resp.Body.Close() body, _ := ioutil.ReadAll(resp.Body) defer req.Body.Close() return string(body)
大约一年之前 回复
weixin_42654444
昨夜是今晨的开始 请问http.NewRequest有访问个数限制吗,由于我是并发访问的,同时http.NewRequest的可能有几百上千,需要设置什么吗
大约一年之前 回复

奇怪,采纳功能去哪了

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问