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
    • 最新
    • 标签
主页 / user-16461952

Ergest Basha's questions

Martin Hope
Ergest Basha
Asked: 2024-09-30 20:53:23 +0800 CST

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

  • 7

我正在尝试使用 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 个回答
  • 85 Views

Sidebar

Stats

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

    重新格式化数字,在固定位置插入分隔符

    • 6 个回答
  • Marko Smith

    为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会?

    • 2 个回答
  • Marko Smith

    VScode 自动卸载扩展的问题(Material 主题)

    • 2 个回答
  • Marko Smith

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

    • 1 个回答
  • Marko Smith

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

    • 1 个回答
  • Marko Smith

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

    • 6 个回答
  • Marko Smith

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

    • 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 个回答
  • Martin Hope
    Fantastic Mr Fox msvc std::vector 实现中仅不接受可复制类型 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant 使用 chrono 查找下一个工作日 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor 构造函数的成员初始化程序可以包含另一个成员的初始化吗? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský 为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul C++20 是否进行了更改,允许从已知绑定数组“type(&)[N]”转换为未知绑定数组“type(&)[]”? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann 为什么 {2,3,10} 和 {x,3,10} (x=2) 的顺序不同? 2025-01-13 23:24:07 +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

热门标签

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