生成 HTTP 文件

概览
目标: 从截获的 API 请求创建 HTTP 文件以供重复使用
时间: 10 分钟
Plugins:HttpFileGeneratorPlugin
先决条件:设置开发代理

使用开发代理可以从截获的 API 请求和响应生成 HTTP 文件。 对于想要模拟 API 行为或共享可重现的 API 交互的开发人员,使用 HTTP 文件特别有用。 HTTP 文件包括所有相关的请求和响应详细信息,其中敏感信息由变量替换,用于安全性和可重用性。

使用开发代理生成 HTTP 文件:

  1. 在配置文件中,启用 HttpFileGeneratorPlugin

    文件: devproxyrc.json

    {
      "$schema": "https://raw.githubusercontent.com/dotnet/dev-proxy/main/schemas/v2.0.0/rc.schema.json",
      "plugins": [
        {
          "name": "HttpFileGeneratorPlugin",
          "enabled": true,
          "pluginPath": "~appFolder/plugins/DevProxy.Plugins.dll",
          "configSection": "httpFileGeneratorPlugin"
        }
      ],
      "urlsToWatch": [
        "https://api.example.com/*"
      ],
      "httpFileGeneratorPlugin": {
        "$schema": "https://raw.githubusercontent.com/dotnet/dev-proxy/main/schemas/v2.0.0/httpfilegeneratorplugin.schema.json",
        "includeOptionsRequests": false
      }
    }
    
  2. (可选)通过在 httpFileGeneratorPlugin 节中添加 includeOptionsRequests 属性来配置插件。 此属性确定是否在生成的 HTTP 文件中包括 OPTIONS 请求。 默认值为 false

  3. 在配置文件中的监视 URL 列表里,添加您想要为其生成 HTTP 文件的 API URL。

    完整的配置文件如下所示。

    文件: devproxyrc.json

    {
      "$schema": "https://raw.githubusercontent.com/dotnet/dev-proxy/main/schemas/v2.0.0/rc.schema.json",
      "plugins": [
        {
          "name": "HttpFileGeneratorPlugin",
          "enabled": true,
          "pluginPath": "~appFolder/plugins/DevProxy.Plugins.dll",
          "configSection": "httpFileGeneratorPlugin"
        }
      ],
      "urlsToWatch": [
        "https://api.example.com/*"
      ],
      "httpFileGeneratorPlugin": {
        "$schema": "https://raw.githubusercontent.com/dotnet/dev-proxy/main/schemas/v2.0.0/httpfilegeneratorplugin.schema.json",
        "includeOptionsRequests": false
      }
    }
    
  4. 启动开发代理:

    devproxy
    
  5. r键开始录制请求。

  6. 执行要包含在 HTTP 文件中的 API 请求。

  7. 通过按 s.. 停止录制。

  8. 开发代理生成 HTTP 文件并将其保存在当前目录中。 该文件包括所有捕获的请求和响应,其中包含由变量替换的敏感数据,例如持有者令牌和 API 密钥。 例如:

    @jsonplaceholder_typicode_com_api_key = api-key
    ###
    # @name getPosts
    GET https://jsonplaceholder.typicode.com/posts?api-key={{jsonplaceholder_typicode_com_api_key}}
    Host: jsonplaceholder.typicode.com
    User-Agent: curl/8.6.0
    Accept: */*
    Via: 1.1 dev-proxy/0.29.0
    

    插件会自动为每个主机名和敏感参数组合创建变量,并在适用时跨请求重用它们。

两个命令提示符窗口的屏幕截图。其中一个显示开发代理记录 API 请求。另一个显示生成的 HTTP 文件。

后续步骤

详细了解 HttpFileGeneratorPlugin。

另请参阅