当我用Perl的^{
405: Method Not Allowed
但是,当我用Perl的^{Requests
向同一个URL发送POST请求时,我得到一个“success”响应。GET请求同时适用于REST::Client
和Python。在
我该怎么解决这个问题?在
下面是使用REST::Client
(返回HTTP 405)的代码:
下面是使用LWP::UserAgent
(返回HTTP 200)的代码:
#!/use/bin/perl -w
use strict;
use LWP::UserAgent;
use Data::Dumper;
use JSON;
my $ua = LWP::UserAgent->new;
my $req = HTTP::Request->new(POST => 'URL');
$req->header('Auth' => '04211b77df');
$req->header('Content-type' => 'application/json');
$req->header('Accept' => 'application/json');
my %body = (
'sid' => '001',
'pid' => 'c7b3d83',
'file' => [
{
'name' => 'file1.txt',
'location' => 'folderA'
},
{
'name' => 'file2.txt',
'location' => 'folderB'
}
]
);
$req->content(encode_json(\%body));
$ua->request($req);
以下是Python代码(返回HTTP 200):
import requests, json, sys
headers = {
'Auth': '04211b77df'
'Accept': 'application/json'
'Content-type': 'application/json'
}
data={
'sid': '001',
'pid': 'c7b3d83',
'file': [
{
'name': 'file1.txt',
'location': 'folderA'
},
{
'name': 'file2.txt',
'location': 'folderB'
}
]
}
requests.request('POST', 'URL', data=data, headers=headers)
您的REST::Client代码和LWP::UserAgent代码生成的请求几乎相同。*但是,REST::Client在幕后使用了LWP::UserAgent,它用
$ua->simple_request()
发送请求,而LWP::UserAgent代码使用$ua->request()
。在根据documentation:
我猜是身份验证造成了这个问题。我还猜测,您使用的API不需要对GET请求进行身份验证,因为您说过这些请求是使用REST::Client的。在
要修复此问题,请在构造函数中将^{} 选项设置为
1
:或调用
^{pr2}$setFollow
方法:这将正确处理身份验证响应,但也将遵循重定向。不幸的是,您不能单独设置重定向和身份验证的行为,这是一个long-standing bug。在
*唯一的区别是REST::Client添加了一个
Content-length
头,我认为这无关紧要。在发送之前转储REST::客户端请求:
发送前转储LWP::UserAgent请求:
在实际发送请求时,还会有其他细微的差异,比如用户代理字符串,但我不认为它们与您的问题有关。在
相关问题 更多 >
编程相关推荐