微信相关接口
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

127 lines
2.3 KiB

  1. package wechat
  2. import (
  3. "bytes"
  4. "encoding/xml"
  5. "io/ioutil"
  6. "net/http"
  7. "strings"
  8. )
  9. /**
  10. * 自定义HTTP请求
  11. */
  12. func SendHttp(method, url string, param map[string]string, header ...map[string]string) ([]byte, error) {
  13. httpClient := &http.Client{}
  14. paramStr := ""
  15. if len(param) > 0 {
  16. for key, value := range param {
  17. paramStr += key + "=" + value + "&"
  18. }
  19. paramStr = paramStr[0 : len(paramStr)-1]
  20. }
  21. req, err := http.NewRequest(method, url, strings.NewReader(paramStr))
  22. if err != nil {
  23. return []byte(""), err
  24. }
  25. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  26. if len(header) > 0 {
  27. for _, item := range header {
  28. for k, v := range item {
  29. req.Header.Set(k, v)
  30. }
  31. }
  32. }
  33. resp, err := httpClient.Do(req)
  34. if err != nil {
  35. return []byte(""), err
  36. }
  37. defer resp.Body.Close()
  38. body, err := ioutil.ReadAll(resp.Body)
  39. if err != nil {
  40. return []byte(""), err
  41. }
  42. return body, nil
  43. }
  44. /**
  45. * send xml
  46. */
  47. func SendXml(method, url string, requestxml interface{}, header ...map[string]string) ([]byte, error) {
  48. bytexml, err := xml.Marshal(&requestxml)
  49. if err != nil {
  50. return []byte(""), err
  51. }
  52. httpClient := &http.Client{}
  53. req, err := http.NewRequest(method, url, bytes.NewBuffer(bytexml))
  54. if err != nil {
  55. return []byte(""), err
  56. }
  57. req.Header.Add("Content-Type", "application/xml; charset=utf-8")
  58. if len(header) > 0 {
  59. for _, item := range header {
  60. for k, v := range item {
  61. req.Header.Add(k, v)
  62. }
  63. }
  64. }
  65. resp, err := httpClient.Do(req)
  66. if err != nil {
  67. return []byte(""), err
  68. }
  69. defer resp.Body.Close()
  70. body, err := ioutil.ReadAll(resp.Body)
  71. if err != nil {
  72. return []byte(""), err
  73. }
  74. return body, nil
  75. }
  76. /**
  77. * post 请求
  78. */
  79. func PostJson(url string, param []byte, header ...map[string]string) ([]byte, error) {
  80. httpClient := &http.Client{}
  81. req, err := http.NewRequest("POST", url, bytes.NewBuffer(param))
  82. if err != nil {
  83. return []byte(""), err
  84. }
  85. req.Header.Set("Content-Type", "application/json")
  86. if len(header) > 0 {
  87. for _, item := range header {
  88. for k, v := range item {
  89. req.Header[k] = []string{v}
  90. }
  91. }
  92. }
  93. resp, err := httpClient.Do(req)
  94. if err != nil {
  95. return []byte(""), err
  96. }
  97. defer resp.Body.Close()
  98. body, err := ioutil.ReadAll(resp.Body)
  99. if err != nil {
  100. return []byte(""), err
  101. }
  102. return body, nil
  103. }