Go使用HTTPClient发送Get Post请求
生活随笔
收集整理的這篇文章主要介紹了
Go使用HTTPClient发送Get Post请求
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Get請求
url := c.Host + WarningNumreq, err := http.NewRequest("GET", url, nil)q := req.URL.Query()q.Add("psaId", paramGet.PsaId)q.Add("paasZoneCode", paramGet.PaasZoneCode)req.URL.RawQuery = q.Encode()req.Header.Add("Content-Type", "application/json")if err != nil {return 0, err}client := &http.Client{}rsp, err := client.Do(req)if err != nil {return 0, err}defer rsp.Body.Close()if rsp.StatusCode != http.StatusOK && rsp.StatusCode != http.StatusNoContent {return 0, fmt.Errorf("http response status error code: %v", rsp.StatusCode)}var rspData new_panel.WarnNumResponsedecoder := json.NewDecoder(rsp.Body)err = decoder.Decode(&rspData)if err != nil {return 0, err}if rspData.Status != "0000" {if rspData.Status == "0001" {return 0, err} else {return 0, fmt.Errorf("ClientAlertManager.GetWarnNum Error")}}return rspData.Data.TotalValue, nilPost請求
url := c.Host + TagListbodyBytes, err := json.Marshal(param)if err != nil {return nil, err}req, err := http.NewRequest("POST", url, bytes.NewBuffer(bodyBytes))if err != nil {return nil, err}req.Header.Add("Content-Type", "application/json")client := &http.Client{}rsp, err := client.Do(req)if err != nil {return nil, err}defer rsp.Body.Close()if rsp.StatusCode != http.StatusOK && rsp.StatusCode != http.StatusNoContent {return nil, fmt.Errorf("http response status error code: %v", rsp.StatusCode)}var rspData new_panel.HttpClusterTagListdecoder := json.NewDecoder(rsp.Body)err = decoder.Decode(&rspData)if err != nil {return nil, err}if rspData.Status != "0000" {if rspData.Status == "0001" {return nil, nil} else {return nil, fmt.Errorf("ClientMetaData.GetResourceTree")}}return rspData, nilGet Post混合請求
url := c.Host + WarningNumbodyBytes, err := json.Marshal(paramPost)if err != nil {return 0, err}req, err := http.NewRequest("POST", url, bytes.NewBuffer(bodyBytes))q := req.URL.Query()q.Add("psaId", paramGet.PsaId)q.Add("paasZoneCode", paramGet.PaasZoneCode)req.URL.RawQuery = q.Encode()req.Header.Add("Content-Type", "application/json")if err != nil {return 0, err}client := &http.Client{}rsp, err := client.Do(req)if err != nil {return 0, err}defer rsp.Body.Close()if rsp.StatusCode != http.StatusOK && rsp.StatusCode != http.StatusNoContent {return 0, fmt.Errorf("http response status error code: %v", rsp.StatusCode)}var rspData new_panel.WarnNumResponsedecoder := json.NewDecoder(rsp.Body)err = decoder.Decode(&rspData)if err != nil {return 0, err}if rspData.Status != "0000" {if rspData.Status == "0001" {return 0, err} else {return 0, fmt.Errorf("ClientAlertManager.GetWarnNum Error")}}return rspData.Data.TotalValue, nil總結
以上是生活随笔為你收集整理的Go使用HTTPClient发送Get Post请求的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Go的string/int/int64转
- 下一篇: 利息5厘是多少