简体   繁体   English

如何在Perl和FastCGI中处理和发送POST请求?

[英]How do I handle and send POST requests in Perl and FastCGI?

Unfortunately, I'm not familiar with Perl, so asking here. 不幸的是,我不熟悉Perl,所以问这里。 Actually I'm using FCGI with Perl. 实际上我正在使用Perl的FCGI。

I need to 1. accept a POST request -> 2. send it via POST to another url -> 3. get results -> 4. return results to the first POST request (4 steps). 我需要1.接受POST请求 - > 2.通过POST将其发送到另一个URL - > 3.获取结果 - > 4.将结果返回到第一个POST请求(4个步骤)。

To accept a POST request (step 1) I use the following code (found it somewhere in the Internet): 要接受POST请求(步骤1),我使用以下代码(在Internet的某处找到它):

$ENV{'REQUEST_METHOD'} =~ tr/a-z/A-Z/;
if ($ENV{'REQUEST_METHOD'} eq "POST") {
    read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
}
else {
    print ("some error");
}

@pairs = split(/&/, $buffer);
foreach $pair (@pairs) {
    ($name, $value) = split(/=/, $pair);
    $value =~ tr/+/ /;
    $value =~ s/%(..)/pack("C", hex($1))/eg;
    $FORM{$name} = $value;  
}

The content of $name (it's a string) is the result of the first step. $name (它是一个字符串)的内容是第一步的结果。 Now I need to send $name via POST request to some_url (step 2) which returns me another result (step 3), which I have to return as a result to the very first POST request (step 4). 现在我需要通过POST请求将$name发送到some_url(步骤2),这会返回另一个结果(步骤3),我必须将其返回到第一个POST请求(步骤4)。

Any help with this would be greatly appreciated. 任何有关这方面的帮助将不胜感激。

Thank you. 谢谢。

To accept the POST, you can use the hand-rolled code you've shown, but the very best way is to make use of CGI (which is now a core module so it should be in your Perl distribution). 要接受POST,您可以使用您展示的手动代码,但最好的方法是使用CGI (现在它是一个核心模块,因此它应该在您的Perl发行版中)。 For passing on a POST to somewhere else, you can use LWP::UserAgent 要将POST传递到其他位置,可以使用LWP :: UserAgent

#/usr/bin/perl
use strict;
use warnings;
use CGI;
use LWP::UserAgent;

my $cgi = CGI->new;   # Will process post upon instantiation
my %params = $cgi->Vars;
my $ua = LWP::UserAgent->new;
my $postTo = 'http://www.somewhere.com/path/to/script';
my $response = $ua->post($postTo, %params);

if ($response->is_success) {
    print $response->decoded_content;  # or maybe $response->content in your case
} else {
 die $response->status_line;
}




}

I highly recommend that you do not try to solve this problem yourself but instead use existing libraries to make you life MUCH easier. 强烈建议您不要尝试自己解决这个问题,而是使用现有的库来让您的生活变得更轻松。 The best part of Perl is the vast collection of existing libraries. Perl最好的部分是现有库的大量集合。 See http://search.cpan.org/ http://search.cpan.org/

Good starting places include CGI.pm or a web framework like Catalyst. 良好的起点包括CGI.pm或像Catalyst这样的Web框架。

The code you've quoted is very buggy. 你引用的代码非常错误。 Coincidentally, there was just a post by a popular Perl blogger dissecting this exact code. 巧合的是, 一位颇受欢迎的Perl博主发布了一篇解释这段确切代码的帖子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM