【问题标题】:Failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request - PHP Error打开流失败:HTTP 请求失败! HTTP/1.1 400 错误请求 - PHP 错误
【发布时间】:2021-06-16 01:58:52
【问题描述】:

解决方案:我的负载正文的 JSON 数据格式错误。 "ttl" => 30 在不正确的 array() 方法中。这可能对将来的任何人都没有帮助,移动 ttl 键/值对使其正常工作,如下所示。

$data = array( 
    "statement" => array( 
        "actor" => array(
            "mbox" => "mailto:test@example.com"
        ),
    ),
    "ttl" => 30
);

我检查了许多其他 StackOverflow 问题,但找不到有效的解决方案。我应该注意,我正在使用在端口 8080 上运行的本地 XAMPP 服务器进行测试。不确定这是否重要。我已经能够使用 Postman 来完成这项工作,但是将其转换为 PHP 一直存在问题。我错过了什么吗?我对 PHP 不是很熟悉,但工作需要这个。

编辑:有关 API 预期的更多信息。这是一个相当简单的 API,需要 JSON 正文、基本授权标头和 Content-Type:application/json。

这是我在 Postman 中使用的 JSON 正文。这是 Postman 的直接复制/粘贴,已成功与 API 通信:

{
    "statement": {
        "actor": {
            "mbox": "mailto:test@example.com"
        }
    },
    "ttl": 30
}

我下面的 PHP 代码中是否存在语法错误?同样,我正在动态学习 PHP,所以我不确定我是否使用 PHP 中的 array() 方法正确构建了 JSON 有效负载。

出于明显的安全原因,我下面的代码更改了$https_user$https_password$url 域。在我的实际 PHP 代码中,我拥有 Postman 中使用的相同凭据和域。

$randomSessionID 除了为将来的请求提供标识号外,没有任何实际用途。对 API 响应失败或成功没有影响。

<?php
$https_user = 'username';
$https_password = 'password';
$randomSessionID = floor((mt_rand() / mt_getrandmax()) * 10000000);

$url = 'https://www.example.com/session/' . $randomSessionID . '/launch';

$json = json_encode(array( 
    "statement" => array( 
        "actor" => array(
            "mbox" => "mailto:test@example.com"
        ),"ttl" => 30 
    )
));

$options = array(
    'http' => array(
        'method'  => 'POST',
        'header'  => 'Content-Type: application/json\r\n'.
        "Authorization: Basic ".base64_encode("$https_user:$https_password")."\r\n",
        'content' => $json
    )
);

$context  = stream_context_create($options);

$result = file_get_contents($url, false, $context);

if ($result === FALSE) { /* Handle error */ }

?>

【问题讨论】:

  • 无论您发送给什么,都抱怨了一个错误的请求。由于您没有详细说明这是什么,或者请求格式应该是什么,因此很难看出我们能提供什么帮助。
  • 这意味着您发送到的任何 URL 在POST 期间由于格式错误的数据/语法而拒绝访问这可能是因为您发送的数据无效。也可能是因为页面 METHOD 只允许 GETPUT - 确实有很多原因会导致 400 错误,包括错误配置的“接收”页面。
  • 我更新了我的原始帖子,提供了有关 API 要求的更多信息。非常感谢您能提供的任何帮助!

标签: php http-post


【解决方案1】:

解决方案:我的负载正文的 JSON 数据格式错误。 "ttl" =&gt; 30 在不正确的 array() 方法中。这可能对将来的任何人都没有帮助,但是移动 ttl 键/值对可以使其正常工作,如下所示。

$data = array( 
    "statement" => array( 
        "actor" => array(
            "mbox" => "mailto:test@example.com"
        ),
    ),
    "ttl" => 30
);

【讨论】:

    猜你喜欢
    • 2011-05-31
    • 2015-04-10
    • 1970-01-01
    • 2020-12-18
    • 1970-01-01
    • 2012-04-08
    • 1970-01-01
    • 2012-12-31
    相关资源
    最近更新 更多