Go的HttpClient实现
Go作为相对java更新的语言,本身的http模块就有客户端请求的实现,继上一章Java的实现,这里记录Go的实现,接下来还有python的实现
注(go版本1.6)
package main import ( "encoding/json" "fmt" "io/ioutil" "net/http" "strings" ) func main() { url := "https://xxx" prama := "data=123456"" tokenRes := GetTokenReq(url, prama) fmt.Println(tokenRes ) } func GetTokenReq(url string, parama string) map[string]string { client := &http.Client{} req, err := http.NewRequest("POST", url, strings.NewReader(parama)) req.Header.Add("Content-Type", "application/x-www-form-urlencoded") resp, err := client.Do(req) if err != nil { fmt.Println(err) } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Println(err) } jsonStr := string(body) fmt.Println("jsonStr", jsonStr) var dat map[string]string if err := json.Unmarshal([]byte(jsonStr), &dat); err == nil { fmt.Println("token", dat["token"]) } else { fmt.Println("json str to struct error") } return dat }