微信相关接口
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

package wechat
import (
"bytes"
"encoding/xml"
"io/ioutil"
"net/http"
"strings"
)
/**
* 自定义HTTP请求
*/
func SendHttp(method, url string, param map[string]string, header ...map[string]string) ([]byte, error) {
httpClient := &http.Client{}
paramStr := ""
if len(param) > 0 {
for key, value := range param {
paramStr += key + "=" + value + "&"
}
paramStr = paramStr[0 : len(paramStr)-1]
}
req, err := http.NewRequest(method, url, strings.NewReader(paramStr))
if err != nil {
return []byte(""), err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
if len(header) > 0 {
for _, item := range header {
for k, v := range item {
req.Header.Set(k, v)
}
}
}
resp, err := httpClient.Do(req)
if err != nil {
return []byte(""), err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return []byte(""), err
}
return body, nil
}
/**
* send xml
*/
func SendXml(method, url string, requestxml interface{}, header ...map[string]string) ([]byte, error) {
bytexml, err := xml.Marshal(&requestxml)
if err != nil {
return []byte(""), err
}
httpClient := &http.Client{}
req, err := http.NewRequest(method, url, bytes.NewBuffer(bytexml))
if err != nil {
return []byte(""), err
}
req.Header.Add("Content-Type", "application/xml; charset=utf-8")
if len(header) > 0 {
for _, item := range header {
for k, v := range item {
req.Header.Add(k, v)
}
}
}
resp, err := httpClient.Do(req)
if err != nil {
return []byte(""), err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return []byte(""), err
}
return body, nil
}
/**
* post 请求
*/
func PostJson(url string, param []byte, header ...map[string]string) ([]byte, error) {
httpClient := &http.Client{}
req, err := http.NewRequest("POST", url, bytes.NewBuffer(param))
if err != nil {
return []byte(""), err
}
req.Header.Set("Content-Type", "application/json")
if len(header) > 0 {
for _, item := range header {
for k, v := range item {
req.Header[k] = []string{v}
}
}
}
resp, err := httpClient.Do(req)
if err != nil {
return []byte(""), err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return []byte(""), err
}
return body, nil
}