post请求;multipart/form-data类型
// 构建请求参数requestData := map[string]interface{}{"gb": "","code": "","reMemberInfo": map[string]interface{}{"shi": "","qu": "",},}// 将请求参数编码为JSON格式requestDataJSON, err := json.Marshal(requestData)if err != nil {return "将请求参数编码为JSON格式失败", err}// 目标URLurl := "http://www.xxxx.cn/xxxx"// 准备要发送的数据 ;三个参数orderNo := ""orderData := string(requestDataJSON) // 特殊情况,正常不需要这种数据source := ""// 创建一个Buffer用于构建multipart请求体body := &bytes.Buffer{}writer := multipart.NewWriter(body)// 添加orderNo参数orderNoField, _ := writer.CreateFormField("orderNo")orderNoField.Write([]byte(orderNo))// 添加orderData参数orderDataField, _ := writer.CreateFormField("orderData")orderDataField.Write([]byte(orderData))// 添加source参数sourceField, _ := writer.CreateFormField("source")sourceField.Write([]byte(source))// 关闭multipart写入器writer.Close()// 创建一个HTTP请求request, err := http.NewRequest("POST", url, body)if err != nil {return "创建请求时失败", err}// 设置请求头,指定Content-Type为multipart/form-datarequest.Header.Set("Content-Type", writer.FormDataContentType())// 发送请求client := &http.Client{}response, err := client.Do(request)if err != nil {return "发送请求时出错", err}defer response.Body.Close()// 处理响应if response.StatusCode == http.StatusOK {var responseData map[string]interface{}err = json.NewDecoder(response.Body).Decode(&responseData)if err != nil {return "析响应时出错", err}status, ok := responseData["status"].(string) // status当判断等于true为成功,其他需要根据具体业务修改if !ok {return "解析响应时无法获取状态信息", err}if status == "true" {return "成功", nil} else {statusInfo, ok := responseData["status_info"].(string)if !ok {return "接口返回未提供详细错误信息", err}return "请求失败,状态信息:", err}} else {return "请求失败,状态码:", err}
post请求;application/json类型
requestData := map[string]interface{}{"porder_no": "","pam_gb": []interface{}{},}// 将请求参数转换为JSON格式requestBody, err := json.Marshal(requestData)if err != nil {logc.Errorf(ctx, "无法编码请求数据:", err)return nil, status.Errorf(400, "系统异常")}fmt.Println("请求数据:")fmt.Println(string(requestBody))// 发送POST请求url := "http://"resp, err := http.Post(url, "application/json", bytes.NewBuffer(requestBody))if err != nil {logc.Errorf(ctx, "POST请求失败:", err)return nil, status.Errorf(400, "系统异常")}defer resp.Body.Close()// 读取响应数据responseBody, err := ioutil.ReadAll(resp.Body)if err != nil {logc.Errorf(ctx, "无法读取响应数据:", err)return nil, status.Errorf(400, "系统异常")}// 解析响应JSONvar response map[string]interface{}err = json.Unmarshal(responseBody, &response)if err != nil {logc.Errorf(ctx, "无法解析响应JSON:", err)return nil, status.Errorf(400, "系统异常")}// 打印响应数据fmt.Println("响应数据:")fmt.Println(response)