1

我有一些我正在尝试移植到 ruby​​ 的 perl 代码。perl 代码可以做我想做的事,但是我很难从 ruby​​ 代码中得到类似的结果,这更令人沮丧,因为我所做的并不是非常复杂。

首先,perl代码:

use LWP::UserAgent;
use HTTP::Cookies;

my $cookie_jar  = HTTP::Cookies->new(file => "/home/blah/lwpcookies.txt", autosave => 0);
my $ua      = LWP::UserAgent->new('cookie_jar' => $cookie_jar);

my $p = {
    'param1'    => 'p1val',
    'param2'    => 'p2val',
    'param3'    => 'p3val',
    'param4'    => 'p4val',
    'param5'    => 'p5val',
    'param6'    => 'p6val',
     };

my $res = $ua->post('https://sitename.somesite.com/login_page.php', $p); #login
my $url = "https://sitename.sometime.com/report.php?startdate=2012-1-1&enddate=2012-1-2";
$res = $ua->get($url);

然后我可以访问 $res->content 并从中获取我想要的内容。

我在 ruby​​ 中使用 net/http 进行了同样的尝试,但我无法获得相同的结果。我在弄清楚哪些部分甚至无法正常工作时也遇到了一些麻烦。

这是红宝石代码:

require 'net/http'
params  = Hash.new
params['param1']    = 'p1val'
params['param2']    = 'p2val'
params['param3']    = 'p3val'
params['param4']    = 'p4val'
params['param5']    = 'p5val'
params['param6']    = 'p6val'

uri = URI.parse('https://sitename.somesite.com/login_page.php')
http = Net::HTTP.new(uri.host, uri.port)

http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE

request = Net::HTTP::Post.new(uri.request_uri)
request.set_form_data(params)
res = http.request(request)
cookies = res.response['set-cookie']

# for what it's worth, I'm pretty sure the problem has already occurred by this point
uri = URI.parse("https://sitename.somesite.com/report.php?startdate=2012-1-1&enddate=2012-1-2")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE

request = Net::HTTP::Get.new(uri.request_uri)
request['Cookie'] = cookies

res = http.request(request)

想法?建议?告诉我为什么我是个白痴?谢谢。

4

1 回答 1

3

试试Mechanize,它会为你做 cookie 和重定向:

require 'mechanize'
agent = Mechanize.new
agent.post url1, params

cookie 已设置

response = agent.get url2
于 2012-04-23T00:58:14.880 回答