AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题 / 79039433
Accepted
Ergest Basha
Ergest Basha
Asked: 2024-09-30 20:53:23 +0800 CST2024-09-30 20:53:23 +0800 CST 2024-09-30 20:53:23 +0800 CST

如何使用 Perl 将异步 json 发送到 PHP url?

  • 772

我正在尝试使用 POST 将一些 json 格式的数据发送到特定的 URL test.php。请求应该是异步的,我需要获取 http 响应代码来判断数据是否已发送(我不想等到请求在 test.php 上处理完毕)。

我已经建立了一个 perl 函数来发送数据

#!/usr/bin/perl

use strict;
use warnings;
use JSON qw(encode_json);
use AnyEvent;
use AnyEvent::HTTP;


=pod
Function send asynchronus data , get response code 
=cut
sub sendOutboundPostRequestAsync {
    my ($url, $data, $token) = @_;

    # Create a condition variable to wait for the asynchronous request
    my $request_done = AnyEvent->condvar;

    # Convert the data hash to JSON
    my $json_data = encode_json($data);
    print "JSON data being sent: $json_data\n";  # For debugging

    # Make the HTTP POST request asynchronously
    http_post $url,
        headers => {
            'Authorization' => $token,
            'Content-Type'  => 'application/json',
        },
        body => $json_data,
        sub {
            my ($body, $headers) = @_;
            my $status_code = $headers->{Status} // 500;  # Default to 500 if no status
            
            # Print the response for debugging
            print "Response Body: $body\n";
            print "Request completed with status code: $status_code\n";

            # Send the status code back through the condition variable
            $request_done->send($status_code);
        };

    return $request_done;  # Return the condition variable for further processing
}


#####
my $url = 'http://xxx.xxx.xxx/test.php';
my $token = 'eyJ0eXAiOiJKV1QiLCJhbGci'; 

# Example data to send
my %data = (
    uniqueid => '1727331196.gesti',
    start_time => '2024-09-26 08:13:17',
);

# Call the function
my $response_code_condvar = sendOutboundPostRequestAsync($url, \%data, $token);
my $response_code         = $response_code_condvar->recv;  # Wait for the request to complete

print "Final Response Code: $response_code\n";

获取数据的 php 代码(为了测试目的而缩短)

<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
    
// Retrieve the raw POST data
$postData = file_get_contents('php://input');

// Log all headers for debugging
$headers = getallheaders();
file_put_contents('postData.txt', "Received Headers:\n" . print_r($headers, true) . "\n", FILE_APPEND);

// Specify the file path
$file_path = 'postData.txt';

// Open the file for writing (append mode)
$file = fopen($file_path, 'a'); // Use 'w' to overwrite the file
  
// Write the POST data to the file
fwrite($file, "Received POST data:\n" . $postData . "\n\n");
    
// Close the file
fclose($file);  

// Decode the JSON data
$data = json_decode($postData, true);

// Check if data decoding was successful
if ($data === null) {
    // Handle error: Invalid JSON
    http_response_code(400);
    echo 'Invalid JSON';
    exit;
}

// Extract the action from the decoded data
$action = $data['action'] ?? null;

// Check if the action is set
if ($action === null) {
    // Handle error: Missing action
    http_response_code(400);
    echo 'Missing action';
    exit;
}   
?>

问题

执行 Perl 脚本后我得到

ast1:~ # perl test.agi
JSON data being sent: {"start_time":"2024-09-26 08:13:17","uniqueid":"1727331196.gesti"}
Response Body: Invalid JSON
Request completed with status code: 400
Final Response Code: 400

数据似乎正确,应该可以毫无问题地发送,但在 PHP 端的文本日志中,我得到了

Received POST data:
headers

期望输出

Received POST data:
{
    "start_time": "2024-09-26 08:13:17",
    "uniqueid": "1727331196.gesti"
}

问题

  1. 这是使用 Perl 发送异步数据的最佳方式吗?
  2. 数据结果为空可能是什么问题?
  • 1 1 个回答
  • 85 Views

1 个回答

  • Voted
  1. Best Answer
    hobbs
    2024-09-30T23:39:37+08:002024-09-30T23:39:37+08:00

    你正在做的

    http_post $url, headers => {...}, body => $json_data, sub {... }
    

    但这与文档中的签名不符,文档中写道

    http_post $url, $body, key => value..., $cb->($data, $headers)
    

    也就是说,主体是第二个参数,而不是作为键值对传递的。由于顺序错误,它会被解释headers为主体,并混淆其他所有内容。

    因此,如果您想在示例中使用http_post(而不是http_request),则应为

    http_post $url, $json_data, headers => { ... }, sub { ... }
    
    • 3

相关问题

  • 将复制活动的序列号添加到 Blob

  • Packer 动态源重复工件

  • 选择每组连续 1 的行

  • 图形 API 调用列表 subscribedSkus 状态权限不足,但已授予权限

  • 根据列值创建单独的 DF 的函数

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    为什么这个简单而小的 Java 代码在所有 Graal JVM 上的运行速度都快 30 倍,但在任何 Oracle JVM 上却不行?

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    何时应使用 std::inplace_vector 而不是 std::vector?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Marko Smith

    我正在尝试仅使用海龟随机和数学模块来制作吃豆人游戏

    • 1 个回答
  • Martin Hope
    Aleksandr Dubinsky 为什么 InetAddress 上的 switch 模式匹配会失败,并出现“未涵盖所有可能的输入值”? 2024-12-23 06:56:21 +0800 CST
  • Martin Hope
    Phillip Borge 为什么这个简单而小的 Java 代码在所有 Graal JVM 上的运行速度都快 30 倍,但在任何 Oracle JVM 上却不行? 2024-12-12 20:46:46 +0800 CST
  • Martin Hope
    Oodini 具有指定基础类型但没有枚举器的“枚举类”的用途是什么? 2024-12-12 06:27:11 +0800 CST
  • Martin Hope
    sleeptightAnsiC `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它? 2024-11-09 07:18:53 +0800 CST
  • Martin Hope
    The Mad Gamer 何时应使用 std::inplace_vector 而不是 std::vector? 2024-10-29 23:01:00 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST
  • Martin Hope
    MarkB 为什么 GCC 生成有条件执行 SIMD 实现的代码? 2024-02-17 06:17:14 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve