curl命令行等效于此perl代码

时间:2015-08-05 20:40:03

标签: perl curl

我想为与此Perl代码等效的POST请求编写curl命令:

use strict;
use warnings;
use LWP::UserAgent;
my $base = 'http://www.uniprot.org/mapping/';
my $params = {
  from => 'ACC',
  to => 'P_REFSEQ_AC',
  format => 'tab',
  query => 'P13368'
};
my $agent = LWP::UserAgent->new();
push @{$agent->requests_redirectable}, 'POST';
my $response = $agent->post($base, $params);
$response->is_success ?
  print $response->content :
  die 'Failed, got ' . $response->status_line .
    ' for ' . $response->request->uri . "\n";

我尝试过(以及许多其他变体):

curl -X POST -H "Expect:" --form "from=ACC;to=P_REFSEQ_AC;format=tab; query=P13368" http://www.uniprot.org/mapping/ -o out.tab

Perl代码检索预期结果,但curl命令行不检索。它从“http://www.uniprot.org/mapping/”检索网页,但不发出POST请求。

我在响应标头中查找了一个错误,但没有发现任何可疑的内容。

> POST http://www.uniprot.org/mapping/ HTTP/1.1
> User-Agent: curl/7.22.0 (x86_64-pc-linux-gnu) libcurl/7.22.0 OpenSSL/1.0.1 zlib/1.2.3.4 libidn/1.23 librtmp/2.3
> Host: www.uniprot.org
> Accept: */*
> Proxy-Connection: Keep-Alive
> Content-Length: 178
> Content-Type: multipart/form-data; boundary=----------------------------164471d8347f
> 
} [data not shown]
* HTTP 1.0, assume close after body
< HTTP/1.0 200 OK
< Server: Apache-Coyote/1.1
< Vary: User-Agent
< Vary: Accept-Encoding
< X-Hosted-By: European Bioinformatics Institute
< Content-Type: text/html;charset=UTF-8
< Date: Wed, 05 Aug 2015 20:32:00 GMT
< X-UniProt-Release: 2015_08
< Access-Control-Allow-Origin: *
< Access-Control-Allow-Headers: origin, x-requested-with, content-type
< X-Cache: MISS from localhost
< X-Cache-Lookup: MISS from localhost:3128
< Via: 1.0 localhost (squid/3.1.20)
< Connection: close
<

我花了将近三天的时间在网上寻找解决方案,但没有什么对我有用。

1 个答案:

答案 0 :(得分:3)

看起来服务器期望数据为application/x-www-form-urlencoded而不是multipart/form-data--form参数一样。以下应该有效:

curl -v -L --data \
  "from=ACC&to=P_REFSEQ_AC&format=tab&query=P13368" \
  http://www.uniprot.org/mapping/ -o out.tab

使用--data,您可以获得预期的内容类型标头,但您必须自己进行编码。 -L curl遵循重定向,此处需要重定向以获取结果数据。

不需要-X POST选项,因为POST是发送数据时的默认方法。而且-H "Expect:"也不需要。