Http Client option getting request url or query parameters

已回答

Is there any option to get request url of query parameter in post process script?

# @no-cookie-jar
< {%
  request.variables.set("id", ["af6dhhhhh46e68c9b5a8b75704042","af6dhhdsadsada8c9b5a8b75704042"])
%}

# @no-log
GET https://example.com/app?appId={{id}}

> {%
  console.log("url:", request.url);
%}

0

Hi Bogumil Dzienis 

There's a way, I have a simple example with the next code that maybe you can adapt to your needs:

### Simple example: get request URL and query parameters in post‑processing script

< {%
  // Pre-request: define an array variable
  request.variables.set("id", [
    "af6d11111146e68c9b5a8b75704042",
    "af6d22222246e68c9b5a8b75704042"
  ]);
%}

# @no-cookie-jar
# @no-log
GET https://httpbingo.org/get?appId={{id[0]}}&appId={{id[1]}}
Accept: application/json
Accept-Encoding: identity

> {%
  // Fully defensive wrapper: never throw, always end with a status line
  (function () {
    try {
      // Log HTTP status if available (helps explain upstream 5xx like 502 Bad Gateway)
      try {
        if (typeof response !== 'undefined') {
          var __status = (response && (response.status || response.statusCode));
          if (__status) console.log("HTTP status:", __status);
        }
      } catch (_) { /* ignore */ }

      // 1) Full resolved URL used for this request
      console.log("request.url =", request.url);

      // Normalize request.url across runtimes: it can be a string or an invokable object in some IDE versions
      function getUrlString(rUrl) {
        // 1) Best effort: attempt to invoke, even if typeof !== 'function' (some runtimes expose invokable host objects)
        try { return String(rUrl()); } catch (_) { /* ignore */ }
        // 1a) Try invoking with request as `this` (some host functions require context)
        try { if (rUrl && rUrl.call) { return String(rUrl.call(request)); } } catch (_) { /* ignore */ }
        try { if (rUrl && rUrl.apply) { return String(rUrl.apply(request, [])); } } catch (_) { /* ignore */ }
        // 2) Fallback: if it is a function, invoke again (covers normal JS functions)
        try { if (typeof rUrl === 'function') { return String(rUrl()); } } catch (_) { /* ignore */ }
        // 3) Last resort: stringify as-is
        try { return String(rUrl); } catch (_) { /* ignore */ }
        return '';
      }

      const reqUrlStr = getUrlString(request.url);
      console.log("normalized request.url =", reqUrlStr);

      // Helper: normalize response.body to a string and read effective URL and args from httpbin echo
      function getBodyString() {
        try {
          if (!response) return '';
          const b = response.body;
          if (b == null) return '';
          // Try common shapes in different runtimes
          try { if (typeof b === 'function') { return String(b.call ? b.call(response) : b()); } } catch (_) { /* ignore */ }
          try { if (b && typeof b.string === 'function') { return String(b.string()); } } catch (_) { /* ignore */ }
          try { if (b && typeof b.text === 'function') { return String(b.text()); } } catch (_) { /* ignore */ }
          try { if (typeof b === 'string') { return b; } } catch (_) { /* ignore */ }
          try { return String(b); } catch (_) { /* ignore */ }
        } catch (_) { /* ignore */ }
        return '';
      }

      // Helper: try to read effective URL and args from echo service (httpbingo/httpbin) response body
      function getEchoFromResponse() {
        try {
          const bodyStr = getBodyString();
          if (!bodyStr) return null;
          const j = JSON.parse(bodyStr);
          if (j && typeof j.url === 'string') {
            return { url: j.url, args: j.args || {} };
          }
        } catch (_) { /* ignore */ }
        return null;
      }

      // 2) Extract query parameters in a way that works even when global URL is not available
      function getQueryParams(urlStr) {
        // Try modern URL API first (available in newer IDE runtimes)
        try {
          if (typeof URL !== 'undefined') {
            const u = new URL(urlStr);
            const params = {};
            // Collect all keys, including duplicates
            u.searchParams.forEach((value, key) => {
              if (params[key]) {
                params[key].push(value);
              } else {
                params[key] = [value];
              }
            });
            console.log("parser: URL API");
            return params;
          }
        } catch (e) {
          // Fall back to manual parsing below
        }

        // Fallback parser for environments without global URL
        const qIndex = urlStr.indexOf('?');
        const hashIndex = urlStr.indexOf('#');
        const end = hashIndex >= 0 ? hashIndex : urlStr.length;
        const qs = qIndex >= 0 ? urlStr.substring(qIndex + 1, end) : '';
        const params = {};
        if (!qs) return params;
        qs.split('&').forEach(pair => {
          if (pair === '') return;
          const eq = pair.indexOf('=');
          const key = decodeURIComponent((eq >= 0 ? pair.substring(0, eq) : pair).replace(/\+/g, ' '));
          const val = decodeURIComponent((eq >= 0 ? pair.substring(eq + 1) : '').replace(/\+/g, ' '));
          if (params[key]) {
            params[key].push(val);
          } else {
            params[key] = [val];
          }
        });
        console.log("parser: fallback");
        return params;
      }

      // Prefer the echo service's echoed URL/args when available for maximum consistency across runtimes.
      // Only fall back to parsing request.url when echo is unavailable.
      let chosenUrl = '';
      let params = {};
      let source = 'response.json';

      const echo = getEchoFromResponse();
      if (echo) {
        chosenUrl = String(echo.url || '');
        params = {};
        for (const k in echo.args) {
          if (!Object.prototype.hasOwnProperty.call(echo.args, k)) continue;
          const v = echo.args[k];
          params[k] = Array.isArray(v) ? v.slice() : [String(v)];
        }
        console.log("parser: response.json");
      } else {
        source = 'request.url';
        chosenUrl = reqUrlStr;
        params = getQueryParams(reqUrlStr);
      }

      // Absolute fallback: derive from request variables when both URL sources are unavailable
      try {
        const needFallback = (!params || Object.keys(params).length === 0) || ((params.appId||[]).length === 0);
        if (needFallback && request && request.variables) {
          const ids = (function(){ try { return request.variables.get('id'); } catch(_) { return null; } })();
          if (ids && (Array.isArray(ids) ? ids.length>0 : true)) {
            const arr = Array.isArray(ids) ? ids.map(String) : [String(ids)];
            params = Object.assign({}, params, { appId: arr });
            if (!chosenUrl) chosenUrl = 'computed-from-variables';
            source = 'variables';
          }
        }
      } catch (_) { /* ignore */ }

      console.log("url source:", source);
      console.log("effective url =", chosenUrl);
      const appIds = params["appId"] || [];
      console.log("appId params:", appIds);

      // Optional: a tiny check to prove values are accessible
      // Do not throw to keep the Services run green; just warn if missing.
      if (appIds.length === 0) {
        console.warn("Warning: No appId query parameters found in request.url");
      }
    } catch (err) {
      try {
        console.error("Post-processing script caught error:", (err && (err.stack || err.message)) || String(err));
      } catch (_) { /* ignore logging errors */ }
    } finally {
      // Always print a terminal success line to make green runs obvious
      try { console.log("Status: OK — post-processing completed without errors"); } catch (_) {}
    }
  })();
%}

If I run the code as is, it shows the next response in “Response Handler” inside the Services tool window:

The output from the response handler script will be shown here.

HTTP status: 200
request.url =
function() {
    return __null_aware_to_string(this.__url.getValue())
  }
normalized request.url = https://httpbingo.org/get?appId=af6d11111146e68c9b5a8b75704042&appId=af6d22222246e68c9b5a8b75704042
parser: fallback
url source: request.url
effective url = https://httpbingo.org/get?appId=af6d11111146e68c9b5a8b75704042&appId=af6d22222246e68c9b5a8b75704042
appId params:
[
  "af6d11111146e68c9b5a8b75704042",
  "af6d22222246e68c9b5a8b75704042"
]
Status: OK — post-processing completed without errors

Script finished

I hope this is exactly what you were looking for. If you have any other questions, please let me know.

0

请先登录再写评论。