http请求在工作很常见了,下面看一下常见的2中http请求方式
if response != nil {
defer response.Body.Close()
}
注意这段代码,先判断response是否nil,如果response是nil,程序会崩溃
package main
import (
"crypto/tls"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strings"
"time"
)
func DoHttpGetSsl(reqParam interface{}, serverUrl string) ([]byte, error) {
if len(serverUrl) <= 0 {
return nil, nil
}
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{Timeout: time.Duration(10 * time.Second),Transport:tr}
marshal, e := json.Marshal(reqParam)
if e != nil {
return nil, e
}
data := string(marshal)
req, err := http.NewRequest("GET", serverUrl, strings.NewReader(data))
if err != nil {
return nil, err
}
response, err := client.Do(req)
if response != nil {
defer response.Body.Close()
}
if err != nil || response == nil {
return nil, err
}
bytes, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, err
}
fmt.Println("3333")
return bytes, nil
}
func main() {
resp, err := http.Get("https://www.googleapis.com/youtube/v3/search?key=xxx&type=video&q=game&order=rating&relevanceLanguage=ru&videoDuration=any&publishedAfter=2020-01-01T00:00:00Z")
if err != nil {
fmt.Println("http.Get err=",err)
return
}
bytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("ioutil.ReadAll err=",err)
return
}
fmt.Println(string(bytes))
}
发送https请求用http.get可以,http.NewRequest那种方法不行