Forum Discussion

BenoitB's avatar
BenoitB
Community Hero
5 years ago
Solved

GetHeader and multiple same key

I need to retrieve a cookie after a call to a Rest api. Not a problem i thought, i'll use aqHttpResponse.GetHeader("Set-Cookie"); But how to retrieve the wanted one if multple Set-Cookie are in the...
  • BenoitB's avatar
    BenoitB
    5 years ago

    So it's bullet-proof working now ...

     

    On same headers, call of extractKeyValueFromHeaders(aqHttpResponse.AllHeaders, "JSESSIONID")

    returns

    "5119F6E864B904735B8870DA08215BCD"


    Call of extractKeyValueFromHeaders(aqHttpResponse.AllHeaders, "JSESSIONID", true)

    returns

    "JSESSIONID=5119F6E864B904735B8870DA08215BCD; Path=/; Secure; HttpOnly"

     

    The revised code is (algorithm working, optimization possible) :

    function extractKeyValueFromHeaders(Headers = "", Key = "", AllValues = false) {
      if (Headers == "")
        throw Error("extractKeyValueFromHeaders() - Header is empty");
      if (Key == "")
        throw Error("extractKeyValueFromHeaders() - Key is missing");
      let headerValue = "";
      Headers = Headers.replace(/\r/g, '');
      let data = Headers.split("\n");
      let pos1, pos2, len;
      for (let i = 0; i < data.length; i++) {
        if (data[i] != "") {
          pos1 = aqString.Find(data[i], ":");
          if (pos1 != -1) {
            pos1 = aqString.Find(data[i], Key, pos1);
            if (pos1 != -1) {
              if (AllValues) {
                pos2 = data[i].length;
                len = pos1;  
              }
              else {
                pos2 = aqString.Find(data[i], ";", pos1);
                if (pos2 == -1)
                  pos2 = data[i].length;
                len = pos1 + Key.length + 1;  
              }
              headerValue = data[i].substr(len, pos2 - len);
              break;
            }  
          }
        }
      }
      return headerValue;
    }