【问题标题】:Which is the best and fastest way to send JSON in post request in PHP?在 PHP 的 post 请求中发送 JSON 的最佳和最快的方法是什么?
【发布时间】:2015-11-07 14:42:11
【问题描述】:

我是 android 开发人员,对 php 有一定的了解。我需要在 php 中发出 post 请求。我找到了两种方法来实现它。

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。使用简单的帖子(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 );

但是,我只想知道哪种方法更好、更有效,为什么? 是否有任何服务器/浏览器或任何与平台相关的问题? 或者有没有其他技术可以实现这一目标? 欢迎提出建议。谢谢

【问题讨论】:

标签: php json curl webserver


【解决方案1】:

最好的实现方式总是

  1. 使用 CURL。

因为这是最快且更可靠的..

【讨论】:

  • 谢谢,您能否详细说明一下,它如何快速可靠? :)
  • 所以,基本上在某些服务器上 file_get_contents 被禁用 & 在这种情况下。执行脚本时会出现错误(或没有响应)..
【解决方案2】:

如果您只是从您的 Android JAVA 代码调用启动的 PHP 脚本中发送 JSON 回复,那么最简单且可能最简单的方法就是将您的 PHP 脚本中的 JSON 字符串发送到 echo

<?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 参与进来,你就打破了简单的生命周期。

【讨论】:

  • 首先谢谢评论...实际上我在我的android设备(如wamp服务器)上使用mysql数据库和本地网络服务器和php..我正在调用我的本地php脚本来获取从本地 mysql 数据库中获取数据并将其发送到服务器端 php 脚本和数据库。
猜你喜欢
  • 2011-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多