Rest插件:设置cookie不起作用

时间:2012-07-05 10:44:51

标签: grails cookies groovy httpclient httpbuilder

我想在经过SSO身份验证的服务器上调用经过身份验证的URL。为此,我正在处理请求HTTPClient的cookie。下面的代码工作正常。

    def cookies = []
    request.getCookies().each {
        def cookie = new BasicClientCookie(it.name, it.value)
        cookie['domain'] = it.domain
        cookie['path'] = it.path
        cookie.secure = true
        cookies.add(cookie)
    }

   // **** Setting cookies using header *****
   def output = withHttp(uri: "https://testserver.com") {
        def builder = delegate;

        def html = get(path : '/testactoin.do', 
            headers:['Cookie':cookies.collect{it.name+"="+it.value}.join("; ")],
            contentType : ContentType.XML, 
            query : 
            [
                query: params.query,
                count: params.count,
                cacheName: 'contentStoreCityState',
                filterString: 'address.country=CA,GB,US'
            ]
        )
        return html
    }

但是,如果我尝试使用api设置cookie,则无效。请参阅下面的代码段:

def cookies = []
request.getCookies().each {
    def cookie = new BasicClientCookie(it.name, it.value)
    cookie['domain'] = it.domain
    cookie['path'] = it.path
    cookie.secure = true
    cookies.add(cookie)
}

def output = withHttp(uri: "https://testserver.com") {
    def builder = delegate;

    // **** Setting cookies using api call *****
    cookies.each {
       builder.client.cookieStore.addCookie(it)
    }

    def html = get(path : '/testactoin.do', 
        contentType : ContentType.XML, 
        query : 
        [
            query: params.query,
            count: params.count,
            cacheName: 'contentStoreCityState',
            filterString: 'address.country=CA,GB,US'
        ]
    )
    return html
}

使用addCookie方法设置Cookie有什么问题?它既不会产生任何异常,也不会产生任何警告信息。

1 个答案:

答案 0 :(得分:0)

在您的第一个代码段中,您正在设置Cookie,但标题实际上是Set-Cookie。