2015-11-07 47 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脚本和数据库。 –