httpclient.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package jpushclient
  2. import (
  3. "bytes"
  4. "io/ioutil"
  5. "net/http"
  6. "time"
  7. )
  8. const (
  9. CHARSET = "UTF-8"
  10. CONTENT_TYPE_JSON = "application/json"
  11. DEFAULT_CONNECTION_TIMEOUT = 20 //seconds
  12. DEFAULT_SOCKET_TIMEOUT = 30 // seconds
  13. )
  14. func SendPostString(url, content, authCode string) (string, error) {
  15. //req := Post(url).Debug(true)
  16. req := Post(url)
  17. req.SetTimeout(DEFAULT_CONNECTION_TIMEOUT*time.Second, DEFAULT_SOCKET_TIMEOUT*time.Second)
  18. req.Header("Connection", "Keep-Alive")
  19. req.Header("Charset", CHARSET)
  20. req.Header("Authorization", authCode)
  21. req.Header("Content-Type", CONTENT_TYPE_JSON)
  22. req.SetProtocolVersion("HTTP/1.1")
  23. req.Body(content)
  24. return req.String()
  25. }
  26. func SendPostBytes(url string, content []byte, authCode string) (string, error) {
  27. req := Post(url)
  28. req.SetTimeout(DEFAULT_CONNECTION_TIMEOUT*time.Second, DEFAULT_SOCKET_TIMEOUT*time.Second)
  29. req.Header("Connection", "Keep-Alive")
  30. req.Header("Charset", CHARSET)
  31. req.Header("Authorization", authCode)
  32. req.Header("Content-Type", CONTENT_TYPE_JSON)
  33. req.SetProtocolVersion("HTTP/1.1")
  34. req.Body(content)
  35. return req.String()
  36. }
  37. func SendPostBytes2(url string, data []byte, authCode string) (string, error) {
  38. client := &http.Client{}
  39. req, err := http.NewRequest("POST", url, bytes.NewBuffer(data))
  40. req.Header.Add("Charset", CHARSET)
  41. req.Header.Add("Authorization", authCode)
  42. req.Header.Add("Content-Type", CONTENT_TYPE_JSON)
  43. resp, err := client.Do(req)
  44. if err != nil {
  45. if resp != nil {
  46. resp.Body.Close()
  47. }
  48. return "", err
  49. }
  50. if resp == nil {
  51. return "", nil
  52. }
  53. defer resp.Body.Close()
  54. r, err := ioutil.ReadAll(resp.Body)
  55. if err != nil {
  56. return "", err
  57. }
  58. return string(r), nil
  59. }