2015-11-07 45 views
-1

我是android開發人員,並在php中有一些知識。我需要在PHP中發佈請求。我找到了兩種方法來實現它。哪一種方法可以在PHP中發送JSON請求?

1.使用CURL。

$url = "your url";  
$content = json_encode("your data to be sent"); 

$curl = curl_init($url); 
curl_setopt($curl, CURLOPT_HEADER, false); 
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($curl, CURLOPT_HTTPHEADER, 
     array("Content-type: application/json")); 
curl_setopt($curl, CURLOPT_POST, true); 
curl_setopt($curl, CURLOPT_POSTFIELDS, $content); 

$json_response = curl_exec($curl); 

$status = curl_getinfo($curl, CURLINFO_HTTP_CODE); 

if ($status != 201) { 
    die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl)); 
} 


curl_close($curl); 

$response = json_decode($json_response, true); 

2.使用簡單的POST(的file_get_contents)。

$options = array(
    'http' => array(
    'method' => 'POST', 
    'content' => json_encode($data), 
    'header'=> "Content-Type: application/json\r\n" . 
       "Accept: application/json\r\n" 
    ) 
); 

$context = stream_context_create($options); 
$result = file_get_contents($url, false, $context); 
$response = json_decode($result); 

但是,我只是想知道哪個是更好和更有效的方式來做到這一點,爲什麼呢? 是否有任何服務器/瀏覽器或任何平臺相關的問題? 或者還有其他技術可以實現嗎? 建議是welcome.Thanks

+1

可能重複的[PHP的cUrl與文件\ _get \ _contents](http://stackoverflow.com/questions/11064980/php-curl-vs-file-get-contents) –

回答

1

最佳的方式實現總是

  1. 使用curl。

,因爲這是最快的&更可靠..

+0

謝謝,請你詳細說明,如何它快速可靠? :) –

+0

http://stackoverflow.com/a/11064995/3181416 –

+0

http://stackoverflow.com/a/14188849/3181416 這也是。 –

0

如果你只是從發送一個呼叫從自己的Android JAVA代碼推出了PHP腳本JSON回覆那麼簡單,可能是禁食僅僅是echo PHP腳本中的JSON字符串。

<?php 

    // read the $_POST inputs from Android call 

    // Process whatever building an array 
    // or better still an object containing all 
    // data and statuses you want to return to the 
    // android JAVA code 

    echo json_encode($theObjectOrArray); 
    exit; 

通過這種方式,相同的交/性反應的一部分。如果你涉及CURL,你就打破了簡單的生命週期。

+0

首先thnx評論...其實我在本地web服務器和php在我的android設備(如wamp服務器)使用mysql數據庫..我打電話給我的本地php腳本從本地mysql數據庫獲取數據併發送它到服務器端的PHP腳本和數據庫。 –