httpclient.go
2.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package socialwork_sdk
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/http/cookiejar"
"strings"
)
const (
post = "POST"
get = "GET"
put = "PUT"
)
func makeHttpRequestV4(method, url string, headers map[string]string, entity map[string]interface{}, jar *cookiejar.Jar) (string, int, error) {
var body io.Reader
var err error
if entity != nil {
switch method {
case post, put:
if len(entity) == 1 && entity["jsonbody"] != nil {
jsonBody, ok := entity["jsonbody"].(string)
if ok {
body = bytes.NewBuffer([]byte(jsonBody))
}
} else {
b, err := json.Marshal(entity)
if err != nil {
return "", 0, err
}
b = bytes.Replace(b, []byte("\\u003c"), []byte("<"), -1)
b = bytes.Replace(b, []byte("\\u003e"), []byte(">"), -1)
b = bytes.Replace(b, []byte("\\u0026"), []byte("&"), -1)
body = bytes.NewBuffer(b)
}
case get:
if len(entity) > 0 {
params := make([]string, len(entity))
index := 0
for k, v := range entity {
_v := fmt.Sprintf("%v", v)
params[index] = fmt.Sprintf("%s=%v", k, _v)
index++
}
queryStr := strings.Join(params, "&")
url = fmt.Sprintf("%s?%s", url, queryStr)
}
}
}
req, err := http.NewRequest(method, url, body)
if err != nil {
return "", 0, err
}
// set the http request header
for key, value := range headers {
req.Header.Set(key, value)
}
if entity != nil && (method == post || method == put) {
req.Header.Set("Content-Type", "application/json;charset=utf-8")
req.Header.Set("Accept", "application/json")
}
req.Header.Add("Connection", "close")
req.Header.Set("User-Agent", "Mozilla/5.0 (X11; Linux i686; U;) Gecko/20070322 Kazehakase/0.4.5")
//跳过证书验证
// tr := &http.Transport{
// TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
// }
client := http.DefaultClient
if jar != nil {
client = &http.Client{
Jar: jar,
}
}
// client.Transport = tr
fmt.Printf("xuht================Request: %+v\n", *req)
res, err := client.Do(req)
if err != nil {
fmt.Println("faild to do the request with error ", err)
return "", 0, err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK && res.StatusCode != http.StatusCreated && res.StatusCode != http.StatusNoContent {
resBody, _ := ioutil.ReadAll(res.Body)
fmt.Println("code is not 200 ", res.StatusCode, string(resBody))
return "", 0, errors.New("http request failed to call")
}
resBody, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println("could not read the response body")
return "", 0, errors.New("the response could not be read")
}
return string(resBody), res.StatusCode, nil
}