我是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
可能重复的[PHP的cUrl与文件\ _get \ _contents](http://stackoverflow.com/questions/11064980/php-curl-vs-file-get-contents) –