Go使用HTTPClient发送Get Post请求

作者: adm 分类: go 发布时间: 2022-12-03

Get请求

    url := c.Host + WarningNum
 
	req, 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.WarnNumResponse
 
	decoder := 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

Post请求

    url := c.Host + TagList
 
	bodyBytes, 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.HttpClusterTagList
 
	decoder := 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, nil

Get Post混合请求

    url := c.Host + WarningNum
 
	bodyBytes, 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.WarnNumResponse
 
	decoder := 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

如果觉得我的文章对您有用,请随意赞赏。您的支持将鼓励我继续创作!