douquejituan938904 2018-02-14 10:22
浏览 88
已采纳

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

After writing the cURL script to to get what I wanted - I found out that the web server doesn't support cURL and only supports pure PHP. How would I go about doing this in pure 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;?>

Is what has managed to work for me.

I have tried this approach for pure 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;?>
?>

However I get this error:

failed to open stream: HTTP request failed!

Thanks!

  • 写回答

2条回答 默认 最新

  • dragon8899 2018-02-14 10:35
    关注

    I can see the problem in the header after each line you have to add (CR LF).

    This is defined here.

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?