3

我疯了,试图弄清楚如何阅读cfhttp.responseHeader. 我正在尝试访问一个在响应中发送几个 cookie 的网站。我需要从响应中提取它们。然后将 cookie 值与所有未来请求一起发送。我尝试使用以下代码:

<cfloop collection = #cfhttp.responseHeader# item = "httpHeader">
  <cfset value = cfhttp.responseHeader[httpHeader]>
    <cfif IsSimpleValue(value)>
      <cfoutput>
      #httpHeader# : #value#<BR>
      </cfoutput>
<cfelse>
      <cfloop index = "counter" from = 1 to = #ArrayLen(value)#>
       <cfoutput>
        #httpHeader# : #value[counter]#<BR> 
       </cfoutput>
 </cfloop>
</cfif>

但这会引发以下错误

Object of type class coldfusion.util.FastHashtable cannot be used as an array  


The error occurred in C:/inetpub/wwwroot/cfdocs/Response.cfm: line 22

20 :     </cfoutput>
21 :   <cfelse>
22 :     <cfloop index = "counter" from = 1 to = #ArrayLen(value)#>
23 :       <cfoutput>
24 :         #httpHeader# : #value[counter]#<BR> 
4

3 回答 3

3

您可以像这样检索 cookie:

<cfset cookies = cfhttp.responseHeader["set-cookie"] />

<cfdump var="#cookies#" />

然后,您可以使用该 cookie 结构数据来发出后续请求。

于 2012-08-06T19:25:32.380 回答
1

这是我使用 Ben Nadel 网站上的参考资料制作的用于获取标头 cookie 的脚本。

public struct function GetResponseCookies(required struct Response){
    var LOCAL = {};
    LOCAL.Cookies = {};

    if(!StructKeyExists(ARGUMENTS.Response.ResponseHeader,"Set-Cookie")){
        return LOCAL.Cookies;
    }

    LOCAL.ReturnedCookies = ARGUMENTS.Response.ResponseHeader[ "Set-Cookie" ];

    if(!isStruct(LOCAL.ReturnedCookies)){
        return LOCAL.Cookies;
    }

    for(LOCAL.CookieIndex in LOCAL.ReturnedCookies){
        LOCAL.CookieString = LOCAL.ReturnedCookies[ LOCAL.CookieIndex ];

        for(LOCAL.Index =1; Local.Index != ListLen( LOCAL.CookieString, ';' ); LOCAL.Index++){
            LOCAL.Pair = ListGetAt(LOCAL.CookieString,LOCAL.Index,";");
            LOCAL.Name = ListFirst( LOCAL.Pair, "=" );

            if(ListLen( LOCAL.Pair, "=" ) > 1){
                LOCAL.Value = ListRest( LOCAL.Pair, "=" );
            } else {
                LOCAL.Value = "";
            }

            if(LOCAL.Index EQ 1){
                LOCAL.Cookies[ LOCAL.Name ] = {};
                LOCAL.Cookie = LOCAL.Cookies[ LOCAL.Name ];
                LOCAL.Cookie.Value = LOCAL.Value;
                LOCAL.Cookie.Attributes = {};
            } else {
                LOCAL.Cookie.Attributes[ LOCAL.Name ] = LOCAL.Value;
            }
        }
    }
    return LOCAL.Cookies;   
}
于 2014-11-12T21:46:49.283 回答
1

问题是您试图遍历一个结构,但将其视为一个数组。您需要使用“集合”来循环结构。

<cfloop collection="#cfhttp.responseHeader['set-cookie']#" item="sKey">
    .....
</cfloop>
于 2013-10-28T10:17:46.500 回答