【问题标题】:Retrieve a JSON from postman on PHP在 PHP 上从邮递员那里检索 JSON
【发布时间】:2016-02-27 04:49:16
【问题描述】:

我正在尝试从 api 检索 json(并存储为变量),但我无法检索。 我正在尝试邮递员和网络给我的所有方式。

  1. 我正在使用 laravel/homestead (ubuntu)
  2. 我正在使用 laravel 框架。

这样给我一个 HTTP 状态 415 - 不支持的媒体类型

 <?php

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_PORT => "443",
  CURLOPT_URL => "https://iescities.com:443/IESCities/api/data/query/268/sql?origin=original",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => "select * from wifi",
  CURLOPT_HTTPHEADER => array(
    "cache-control: no-cache",
    "postman-token: 1471daf9-329d-e9b4-b144-0383850f4769"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}

我也尝试了另一种方式,但我没有 http\Client 类,也不知道如何安装和/或链接它。

$client = new http\Client;
$request = new http\Client\Request;

$body = new http\Message\Body;
$body->append('select * from wifi');

$request->setRequestUrl('https://iescities.com:443/IESCities/api/data/query/268/sql');
$request->setRequestMethod('POST');
$request->setBody($body);

$request->setQuery(new http\QueryString(array(
  'origin' => 'original'
)));

$request->setHeaders(array(
  'postman-token' => 'e854f317-fdcc-1888-0043-758a3d5e32ba',
  'cache-control' => 'no-cache'
));

$client->enqueue($request)->send();
$response = $client->getResponse();

echo $response->getBody();

非常感谢并为我的无知感到抱歉。

【问题讨论】:

  • CURLOPT_POSTFIELDS =&gt; "select * from wifi" 这是一名嫌疑人

标签: php json forms laravel


【解决方案1】:

来自IESCities manual

查询必须以文本/纯格式发送。

所以在你设置标题的行中:

CURLOPT_HTTPHEADER => array(
    "cache-control: no-cache",
    "postman-token: 1471daf9-329d-e9b4-b144-0383850f4769"
),

你应该放另一个键:

CURLOPT_HTTPHEADER => array(
    "cache-control: no-cache",
    "postman-token: 1471daf9-329d-e9b4-b144-0383850f4769",
    "Content-Type: text/plain"
),

完成此操作后,您应该能够查询 API。

【讨论】:

    【解决方案2】:

    您是否尝试过解码 JSON?

    $response = curl_exec($curl);
    
    $responseJSON = json_decode($response, true);
    print_r($responseJSON);
    

    如果你的 JSON 看起来像:

    {
        "name": Susy,
        "age": 22
    }
    

    你可以使用echo $responseJSON["age"];拉年龄

    【讨论】:

      猜你喜欢
      • 2018-10-12
      • 1970-01-01
      • 1970-01-01
      • 2018-07-27
      • 2020-11-25
      • 2021-11-23
      • 1970-01-01
      • 1970-01-01
      • 2014-02-22
      相关资源
      最近更新 更多