简体   繁体   English

使用 php 从 API 获取 JSON 响应

[英]Fetch JSON response from API using php

I'm trying to fetch data from API, but no data returns.我正在尝试从 API 获取数据,但没有数据返回。 I try the API request in postman and it's working but in my php code nothing gets returned.我在 postman 中尝试了 API 请求,它正在工作,但在我的 php 代码中没有返回任何内容。

$uri = 'https://example.com';

$opts = array(
  'http' => array(
    'method'=>'POST', 
    'header'=>'Content-Type: application/x-www-form-urlencoded', 
  )
);

$context = stream_context_create($opts);

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

print $result;

or using curl或使用 curl

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://example.com',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'POST',
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;

the error is错误是

file_get_contents(https://example.com): failed to open stream: HTTP request failed! HTTP/1.1 411 Length Required

Note: the response size in postman is 9.83, is this maybe an issue?注意:postman 中的响应大小为 9.83,这可能是个问题吗?


$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,"http://www.example.com/tester.phtml");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
            "postvar1=value1&postvar2=value2&postvar3=value3");

// In real life you should use something like:
// curl_setopt($ch, CURLOPT_POSTFIELDS, 
//          http_build_query(array('postvar1' => 'value1')));

// Receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$server_output = curl_exec($ch);

curl_close ($ch);

// Further processing ...
if ($server_output == "OK") { ... } else { ... }

The issue has been solved by add Content-Length: 0 in the header该问题已通过在 header 中添加 Content-Length: 0 解决

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM