如何在HTTP Builder 0.5.0 / HTTPClient中保存cookie

时间:2010-06-09 22:20:35

标签: cookies httpclient httpbuilder

我正在尝试按照这里的说明: http://www.innovation.ch/java/HTTPClient/advanced_info.html

但是,如果我使用的是HTTP Builder,则需要以下几行

System.setProperty("HTTPClient.cookies.save","true")
System.setProperty("HTTPClient.cookies.jar","/home/misha/.httpclient_cookies")

似乎没有创建文件:

~/.httpclient_cookies

我会一如既往地发布解决方案。

:)

米莎

2 个答案:

答案 0 :(得分:0)

您链接的HTTPClient与与groovy HTTPBuilder捆绑在一起的apache HTTPClient不同。使用apache HTTPClient查看this documentation持久性cookie。

答案 1 :(得分:0)

谢谢。我选择了一个更黑客的解决方案:

#!/usr/bin/env groovy

import com.gargoylesoftware.htmlunit.WebClient

import static groovyx.net.http.Method.GET
import static groovyx.net.http.ContentType.TEXT

import java.io.File

import org.apache.http.impl.cookie.BasicClientCookie

class HTTPBuilder extends groovyx.net.http.HTTPBuilder {

...

  /**
   * Load cookies from specified file
   */
  def loadCookies(file) {
    file.withObjectInputStream { ois->
      ois.readObject().each { cookieMap->
    def cookie=new BasicClientCookie(cookieMap.name,cookieMap.value)
    cookieMap.remove("name")
    cookieMap.remove("value")
    cookieMap.entrySet().each { entry->
      cookie."${entry.key}"=entry.value
    }
    client.cookieStore.addCookie(cookie)
    println cookie
      }
    }
  }

  /**
   * Save cookies to specified file
   */
  def saveCookies(file) {
    def cookieMaps=new ArrayList(new LinkedHashMap())
    client.cookieStore.getCookies().each { cookie->
      def cookieMap=[:]
      cookieMap.version=cookie.version
      cookieMap.name=cookie.name
      cookieMap.value=cookie.value
      cookieMap.domain=cookie.domain
      cookieMap.path=cookie.path
      cookieMap.expiryDate=cookie.expiryDate
      cookieMaps.add(cookieMap)
      println cookie
    }
    file.withObjectOutputStream { oos->
      oos.writeObject(cookieMaps)
    }
  }

...

}