4

我必须从使用 cookie 进行身份验证的 API 中获取数据。这是它与卷曲一起使用。

curl -L -s -c cookie.txt "http://api.domain.com/login" -d username="user@domain.com" -d password="password"  > /dev/null

curl -b cookie.txt "http://api.domain.com/user_data?param1=value1" > output.xml

cat output.xml

以上效果很好

但是我无法使用 Typhoeus 做同样的事情

我尝试了以下方法,它甚至没有进行身份验证。

url = "http://api.domain.com/login"
cookie_file_path = "cookie.txt"
params = {param1: "value1"}
body = {username: "user@domain.com", password: "password"}

request = Typhoeus::Request.new(
  url,
  method: :post,
  params: params,
  body: body,
  cookiejar: cookie_file_path,
  #headers: {Accept: "text/html"},
  verbose: true
)

response = request.run
cookies = CookieJar.new.parse(response.headers_hash["Set-Cookie"])

puts cookies # doesn't show me anything.

url = "http://api.domain.com/user_data"
cookie_file_path = "cookie.txt"
params = {output: "xml"}
body = {}

request = Typhoeus::Request.new(
  url,
  method:        :get,
  params:        params,
  body:        body,
  cookiejar: cookie_file_path,
  cookiefile: cookie_file_path,
  #headers:       {Accept: "text/html"},
  verbose: true
)

我错过了什么?

>>> response.code
302
>>> response.headers_hash
{"Server"=>"squid/3.1.10", "Mime-Version"=>"1.0", "Date"=>"Fri, 14 Jun 2013 02:38:28 GMT", "Content-Type"=>"text/html", "Content-Length"=>"3830", "X-Squid-Error"=>"ERR_INVALID_REQ 0", "Vary"=>"Accept-Language", "Content-Language"=>"en", "X-Cache"=>"MISS from domain.com", "X-Cache-Lookup"=>"NONE from domain.com:3128", "Via"=>"1.0 domain.com (squid/3.1.10)", "Connection"=>"close"}
4

1 回答 1

0

我会发表评论,但不能。看起来您正在获得重定向。尝试添加followlocation: true选项:

request = Typhoeus::Request.new(
  url,
  followlocation: true, # <--
  method: :post,
  params: params,
  body: body,
  cookiejar: cookie_file_path,
  #headers: {Accept: "text/html"},
  verbose: true
)
于 2014-10-07T20:31:36.860 回答