1 package http
2
3 import (
4 "bytes"
5 "encoding/json"
6 "io/ioutil"
7 "net/http"
8 "time"
9 )
10 // 复制代码即可使用
11 // 发送GET请求
12 // url: 请求地址
13 func Get(url string) (string, error) {
14
15 client := &http.Client{}
16 req, err := http.NewRequest("GET", url, nil)
17 req.Header.Set("Accept", "*/*")
18 req.Header.Set("Content-Type", "application/json")
19 if err != nil {
20 return "", err
21 }
22
23 resp, err := client.Do(req)
24 if err != nil {
25 return "", err
26 }
27 defer resp.Body.Close()
28 result, err := ioutil.ReadAll(resp.Body)
29 if err != nil {
30 return "",err
31 }
32 return string(result), nil
33 }
34
35 // 发送POST请求
36 // url: 请求地址
37 // data: POST请求提交的数据
38 // contentType: 请求体格式,如:application/json
39 func Post(url string, data interface{}, contentType string) (string,error) {
40
41 // 超时时间:5秒
42 client := &http.Client{Timeout: 5 * time.Second}
43 jsonStr, err := json.Marshal(data)
44 if err != nil {
45 return "",err
46 }
47 resp, err := client.Post(url, contentType, bytes.NewBuffer(jsonStr))
48 if err != nil {
49 return "",err
50 }
51 defer resp.Body.Close()
52
53 result, err := ioutil.ReadAll(resp.Body)
54 if err != nil {
55 return "",err
56 }
57 return string(result),nil
58 }
59
60 //测试方法post
61 var contentType="application/json"
62 func TestPost(t *testing.T) {
63 url := "http://127.0.0.1:8555"
64 bc_no := strconv.FormatInt(11941, 16)
65 bc_no="0x"+bc_no
66 params:=[]string{bc_no}
67 body :=map[string]interface{}{
68 "jsonrpc":"2.0",
69 "method":"eth_getBlockTransactionCountByNumber",
70 "params":params,
71 "id":time.Now().Unix(),
72 }
73 data,err:=Post(url,body,contentType)
74 if err !=nil {
75 fmt.Printf("eth_getBlockTransactionCountByNumber err:%v",err)
76 return
77 }
78 fmt.Println(string(data))
79
80 }
81
82
83
84
85