forked from Scorpio69t/jpush-api-golang-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttpclient.go
86 lines (74 loc) · 2.55 KB
/
httpclient.go
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
package jpush
import (
"bytes"
"errors"
"io/ioutil"
"net/http"
"time"
)
const (
CHARSET = "UTF-8"
CONTENT_TYPE_JSON = "application/json"
CONTENT_TYPE_FORM = "application/x-www-form-urlencoded"
DEFAULT_CONNECT_TIMEOUT = 60 // Connect timeout in seconds
DEFAULT_READ_WRITE_TIMEOUT = 60 // Read and write timeout in seconds
)
// SendPostString sends a post request and returns the response body as string
func SendPostString(url string, content, appKey, masterSecret string) (string, error) {
req := Post(url)
req.SetTimeout(DEFAULT_CONNECT_TIMEOUT*time.Second, DEFAULT_READ_WRITE_TIMEOUT*time.Second)
req.SetHeader("Connection", "Keep-Alive")
req.SetHeader("Charset", CHARSET)
req.SetBasicAuth(appKey, masterSecret)
req.SetHeader("Content-Type", CONTENT_TYPE_JSON)
req.SetProtocolVersion("HTTP/1.1")
req.SetBody(content)
return req.String()
}
// SendPostBytes sends a post request and returns the response body as bytes
func SendPostBytes(url string, content []byte, appKey, masterSecret string) (string, error) {
req := Post(url)
req.SetTimeout(DEFAULT_CONNECT_TIMEOUT*time.Second, DEFAULT_READ_WRITE_TIMEOUT*time.Second)
req.SetHeader("Connection", "Keep-Alive")
req.SetHeader("Charset", CHARSET)
req.SetBasicAuth(appKey, masterSecret)
req.SetHeader("Content-Type", CONTENT_TYPE_JSON)
req.SetProtocolVersion("HTTP/1.1")
req.SetBody(content)
return req.String()
}
// SendPostBytes2 sends a post request and returns the response body as bytes
func SendPostBytes2(url string, data []byte, appKey, masterSecret string) (string, error) {
client := &http.Client{}
req, err := http.NewRequest("POST", url, bytes.NewBuffer(data))
req.Header.Add("Charset", CHARSET)
req.SetBasicAuth(appKey, masterSecret)
req.Header.Add("Content-Type", CONTENT_TYPE_JSON)
resp, err := client.Do(req)
if err != nil {
if resp != nil {
defer resp.Body.Close()
}
return "", err
}
if resp == nil {
return "", errors.New("response is nil")
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(body), nil
}
// SendGet sends a get request and returns the response body as string
func SendGet(url, appKey, masterSecret string) (string, error) {
req := Get(url)
req.SetTimeout(DEFAULT_CONNECT_TIMEOUT*time.Second, DEFAULT_READ_WRITE_TIMEOUT*time.Second)
req.SetHeader("Connection", "Keep-Alive")
req.SetHeader("Charset", CHARSET)
req.SetBasicAuth(appKey, masterSecret)
req.SetHeader("Content-Type", CONTENT_TYPE_JSON)
req.SetProtocolVersion("HTTP/1.1")
return req.String()
}