设置HTTP :: Request :: Common的头字段

时间:2017-08-08 14:58:57

标签: perl

设置用于通过Perl模块发送请求的标头字段时出现问题' HTTP :: Request :: Common'。

在受相应服务器约束的情况下,我必须为我的请求设置不同的标题字段。

所以我想使用sub' MakeRequest()'

sub MakeRequest {
    my $url = shift;
    my $header = shift;
    my $content = shift;
    my $request = HTTP::Request::Common::POST($url, Header => $header, Content => $content);
    # I tried also my $request = HTTP::Request::Common::POST($url, $header, Content => $content);
    my $ua = LWP::UserAgent->new;
    my $response = $ua->request($request);
    return $response;
}

并将一些信息传递给它my $response = MakeRequest($url, GetRequestHeader(), $content);

sub GetRequestHeader {
    my $header = HTTP::Headers->new;
    $header->header('Content-Type' => 'application/json; charset=utf-8'); 
    $header->header('accept' => 'application/json'); 
    $header->authorization_basic($username, $password);
    return $header;

    # I tried this first, but got the same result as shown below
    #
    #   my %header = ( 
    #       'content_type' => 'application/json; charset=utf-8', 
    #       'authorization_basic' => ($username, $password), 
    #       'accept' =>  'application/json'
    #   );
    # return %header;

}

但我从远程服务器获得的只是这个

  

"内容类型' application / x-www-form-urlencoded'不受支持。   请使用' application / json;字符集= UTF-8'"

当我做print Data::Dumper($request);时,我得到了

'_headers' => bless( {
                       'content-length' => 544,
                       'user-agent' => 'libwww-perl/6.15',
                       'header' => bless( {
                                            'content-type' => 'application/json; charset=utf-8',
                                            'authorization' => 'Basic Qxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx==',
                                            'accept' => 'application/json'
                                          }, 'HTTP::Headers' ),
                       '::std_case' => {
                                         'header' => 'Header',
                                         'if-ssl-cert-subject' => 'If-SSL-Cert-Subject'
                                       },
                       'content-type' => 'application/x-www-form-urlencoded'
                     }, 'HTTP::Headers' ),

'内容类型'我的错误是什么?没有被我的标题字段设置覆盖?

1 个答案:

答案 0 :(得分:2)

根据文件:

HTTP::Request::Common::GET $url, Header => Value,...

相同
HTTP::Request->new(
   GET => $url,
   HTTP::Headers->new(Header => Value,...),
)

我认为你原来的方法(评论)很好,但是你指的是错误的方式:

my $header = shift;
my $content = shift;
my $request = HTTP::Request::Common::POST($url, Header => $header, Content => $content);

在这里,您只创建一个名为Header的标头。如果您有HTTP :: Headers对象,则可以使用以下命令:

my $request = HTTP::Request::Common::POST($url, $header->flatten, Content => $content);

如果您更改GetRequestHeader以返回哈希引用(如您所评论,但使用return \%header而不是return %header),则可以使用以下内容:

my $request = HTTP::Request::Common::POST($url, %$hashref, Content => $content);