php - 在没有 cURL 的情况下在 PHP 中调用 API

标签 php rest api http

在编写了 cURL 脚本以获得我想要的东西之后——我发现网络服务器不支持 cURL,只支持纯 PHP。我将如何在纯 PHP 中执行此操作?

    <?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://xx.xxxx.xxx/xxx/blog/micro");
curl_setopt($ch, CURLOPT_HTTPGET, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$headers = [
    'Header1: Header1Input',
    'Header1: Header2Input',
];

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$server_output = curl_exec ($ch);

curl_close ($ch);
 $json = $server_output;
 $data = json_decode($json);


print  $data[1]->Headline;?>

是什么成功地为我工作。

我已经为纯 PHP 尝试过这种方法:

    <?php

// Create a stream
$opts = [
    "http" => [
            "method" => "GET",
            "header" => "Header1: Header1Input" .
            "Header2: Header2Input"
            ]
        ];

$context = stream_context_create($opts);

// Open the file using the HTTP headers set above
$file = file_get_contents('https://xx.xxxx.xxx/xxx/blog/micro', false, $context);

$file = json_decode($file);


print  $file[1]->Headline;?>
?>

但是我得到这个错误:

failed to open stream: HTTP request failed!

谢谢!

最佳答案

我可以在必须添加 \r\n (CR LF) 的每一行之后的 header 中看到问题。

这是定义here .

HTTP/1.1 defines the sequence CR LF as the end-of-line marker for all protocol elements except the entity-body.

关于php - 在没有 cURL 的情况下在 PHP 中调用 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48784774/

相关文章:

php - Wordpress 数据库连接错误

php - 如何将表格中一行的内容从一个php页面获取到另一个页面?

http - 在 412 "Precondition failed"的情况下是否可以返回实体的最新版本

java - 使用 Java SE 应用程序轻松部署数据库

java - 从 Interactive Brokers Java API 读取 minTick 的问题

java - 错误 - 尝试关闭结果集或准备好的 JDBCResourceDAO 时发生 SQLException 错误

php - .htaccess 在动态文件夹名称中加载索引

android从编辑文本中获取url并在rest api中使用它来上传数据

rest - Nginx 代理在空闲时挂了一会儿

javascript - 我在 php 中查询时遇到问题(0 个结果)