簡體   English   中英

從REST API獲取發布的數據

[英]getting posted data from REST API

我為我的網站創建了一個剩余的APi。 GET方法工作正常。 對於POST方法,api不會將數據發布回去。 我寫了這段代碼,但是由於注意:試圖獲取非對象的屬性

$response = file_get_contents('http://myapi.com/object/post.php');
$data = json_decode($response);

$object->id = $data->id;
$object->name = $data->name;

您可以使用簡單的file_get_contents獲取GET URL,但是要從POST URL獲取數據,您需要使用CURL:

<?php

$post = [
    'postData1' => 'datavalue1',
    'postData2' => 'datavalue2'
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://myapi.com/object/post.php');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
$response = curl_exec($ch);
$data = json_decode($response);

$object->id = $data->id;
$object->name = $data->name;

PHP文檔中說明了在file_get_contents中使用POST。 從手冊頁http://php.net/manual/zh/function.file-get-contents.php

<?php
// Create a stream
$opts = array(
  'http'=>array(
    'method'=>"GET",
    'header'=>"Accept-language: en\r\n" .
              "Cookie: foo=bar\r\n"
  )
);

$context = stream_context_create($opts);

// Open the file using the HTTP headers set above
$file = file_get_contents('http://www.example.com/', false, $context);
?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM