发起网络请求(以POST方式)

package main

import (
   "bytes"
   "encoding/json"
   "errors"
   "fmt"
   "io"
   "net/http"
   "net/url"
)

// HttpPost
// @description 以POST方式发起网络请求
// @param urlString string 请求URL
// @param params map[string]any POST参数
// @return response []byte 请求响应结果
// @return err error 错误对象,若请求成功则为nil
func HttpPost(urlString string, params map[string]any) (response []byte, err error) {
   contentType := "application/x-www-form-urlencoded"

   // 将POST参数转为url.Values类型
   values := url.Values{}
   for key, value := range params {
      values.Add(key, fmt.Sprintf("%v", value))
   }
   body := bytes.NewBufferString(values.Encode())

   var resp *http.Response
   resp, err = http.Post(urlString, contentType, body)
   if err != nil {
      return
   }

   // 关闭网络连接
   defer func(body io.ReadCloser) {
      _ = body.Close()
   }(resp.Body)

   // 状态码非200则请求失败
   if resp.StatusCode != http.StatusOK {
      err = errors.New(resp.Status) // resp.Status 示例值:404 Not Found
      return
   }

   // 将响应体读进buffer
   buffer := bytes.NewBuffer([]byte{})
   _, err = buffer.ReadFrom(resp.Body)
   if err != nil {
      return
   }

   response = buffer.Bytes()

   return
}

func main() {
   urlString := "https://www.domain.com/test.php"

   params := map[string]any{}
   params["username"] = "ZhangSan" // 账号
   params["password"] = "pwd-zs"   // 密码
   params["captcha"] = 10086       // 验证码

   response, err := HttpPost(urlString, params)
   if err != nil {
      fmt.Printf("请求失败:%s", err.Error())
      return
   }

   // 请求成功会返回如下内容(JSON字符串):
   // ---------- 俺是分割线,请无视俺 ----------
   // {
   //    "errcode": 0,
   //    "errmsg": "",
   //    "data": {
   //        "name": "张三",
   //        "gender": "男",
   //        "age": 18
   //    }
   // }
   // ---------- 俺是分割线,请无视俺 ----------
   // 重要提醒①:从结果看errcode参数是int类型,但实际上它是float64类型,断言时要注意

   // JSON字符串转map[string]any
   result := map[string]any{}
   err = json.Unmarshal(response, &result) // 注意这里是传内存地址,不是传值
   if err != nil {
      fmt.Printf("解析响应结果失败:%s", err.Error())
      return
   }

   // 检查响应结果数据格式是否正常(根据errcode参数是否存在来判断)
   _, exist := result["errcode"]
   if !exist {
      fmt.Printf("响应结果数据格式异常")
      return
   }

   // 获取错误码和错误信息
   errcode, _ := result["errcode"].(float64) // 重要提醒:errcode参数是float64类型
   errmsg, _ := result["errmsg"].(string)
   if errcode != 0 {
      fmt.Printf("请求出错:%s", errmsg)
      return
   }

   // 继续获取响应结果里的数据
   data, _ := result["data"].(map[string]any)
   dataName, _ := data["name"].(string)
   dataGender, _ := data["gender"].(string)
   dataAge, _ := data["age"].(float64)

   // 打印所有数据
   fmt.Printf("errcode:%.0f \n", errcode)      // errcode:0
   fmt.Printf("errmsg:%s \n", errmsg)          // errmsg:
   fmt.Printf("data.name:%s \n", dataName)     // data.name:张三
   fmt.Printf("data.gender:%s \n", dataGender) // data.gender:男
   fmt.Printf("data.age:%.0f \n", dataAge)     // data.age:18
}



  被请求页面代码如下:

<?php
$username = isset($_POST['username']) ? (string)$_POST['username'] : '';
$password = isset($_POST['password']) ? (string)$_POST['password'] : '';
$captcha = isset($_POST['captcha']) ? (int)$_POST['captcha'] : '';

function ajax_return($return)
{
    header('Content-Type:application/json; charset=utf-8');
    exit(json_encode($return, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
}

if ($username !== 'ZhangSan' || $password !== 'pwd-zs' || $captcha !== 10086) {
    ajax_return(['errcode' => 1, 'errmsg' => '参数错误']);
}

$data = ['name' => '张三', 'gender' => '男', 'age' => 18];

ajax_return(['errcode' => 0, 'errmsg' => '', 'data' => $data]);

Copyright © 2024 码农人生. All Rights Reserved