如何使用Perl的LWP :: UserAgent访问Closure JavaScript minifier?

时间:2010-08-14 00:03:05

标签: perl http request lwp

我正在努力让Code Closure工作,但不幸的是,总会出现错误。

以下是代码:

use LWP::UserAgent;
use HTTP::Request::Common;
use HTTP::Response;

my $name = 'test.js';
my $agent = new LWP::UserAgent();
$agent->agent("curl/7.21.0 (x86_64-pc-linux-gnu) libcurl/7.21.0 OpenSSL/0.9.8o zlib/1.2.3.4 libidn/1.18");

$res = $agent->request(POST 'http://closure-compiler.appspot.com/compile',
           content_type => 'multipart/form-data',
           content      => [
                   output_info => 'compiled_code',
                           compilation_level => 'SIMPLE_OPTIMIZATIONS',
                   output_format => 'text',
                   js_code => [File::Spec->rel2abs($name)]
                       ]);

if ($res->is_success) {
    $minified = $res->decoded_content;
    print $minified;die;
}

我收到以下错误:

  

错误(13):没有要生成的输出信息,但是请求编译。

这是我使用的api参考: http://code.google.com/intl/de-DE/closure/compiler/docs/api-ref.html

希望有人知道这里出了什么问题。感谢。

2 个答案:

答案 0 :(得分:2)

#!/usr/bin/perl

use strict; use warnings;

use File::Slurp;
use LWP::UserAgent;

my $agent = LWP::UserAgent->new;
my $script = 'test.js';

my $response = $agent->post(
    'http://closure-compiler.appspot.com/compile',
    content_type => 'application/x-www-form-urlencoded',
    content => [
        compilation_level => 'SIMPLE_OPTIMIZATIONS',
        output_info => 'compiled_code',
        output_format => 'text',
        js_code => scalar read_file($script),
    ],
);

if ($response->is_success) {
    my $minified = $response->decoded_content;
    print $minified;
}

输出:

C:\Temp> cat test.js
// ADD YOUR CODE HERE
function hello(name) {
  alert('Hello, ' + name);
}
hello('New user');



C:\Temp> t
function hello(a){alert("Hello, "+a)}hello("New user");

答案 1 :(得分:1)

将js_code传递给要编译的实际代码。尝试(删除form-data content_type标头):

use File::Slurp "read_file";
...
     js_code => scalar( read_file($name) ),

我看到你正在尝试使用POST的文件上传功能;您认为API文档中的内容会让您认为哪些有用?如果那里有东西,我看不到它。