使用PHP发送JSON POST请求

111
我有这个JSON数据:
{ 
    userID: 'a7664093-502e-4d2b-bf30-25a2b26d6021',
    itemKind: 0,
    value: 1,
    description: 'Saude',
    itemID: '03e76d0a-8bab-11e0-8250-000c29b481aa'
}

我需要向JSON URL发布内容:

http://domain/OnLeagueRest/resources/onleague/Account/CreditAccount

我该如何使用PHP发送这个POST请求?


真的,通过 http 充值账户!请使用 https 和 JWS 格式验证发送者的身份! - Hack5
4个回答

162

你可以使用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);

如果我们将JSON对象传递给JSON编码函数,则会出现括号语法错误。 - Rajat

154

不使用任何外部依赖或库:

$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 );

$response 是一个对象。可以像平常一样访问属性,例如 $response->...

其中 $data 是包含您数据的数组:

$data = array(
  'userID'      => 'a7664093-502e-4d2b-bf30-25a2b26d6021',
  'itemKind'    => 0,
  'value'       => 1,
  'description' => 'Boa saudaÁ„o.',
  'itemID'      => '03e76d0a-8bab-11e0-8250-000c29b481aa'
);

注意:如果php.ini文件中的allow_url_fopen设置为Off,则此方法将无法工作。

如果您正在开发WordPress,请考虑使用提供的API:https://developer.wordpress.org/plugins/http-api/


2
@solarshado 可以使用 stream_get_meta_data 获取原始响应头。 - Daniels118
2
一个小的改进建议,你可以把头部信息放在一个数组中,特别是如果需要添加更多的头部信息,比如授权。在这种情况下,不应该添加"\r\n"。 - zero0cool

2

请注意,file_get_contents 解决方案在服务器返回 Connection: close 的 HTTP 头时不会像应该关闭连接。

另一方面,CURL 解决方案终止连接,因此 PHP 脚本不会被等待响应而阻塞。


0

使用CURL吧,说真的,那是最好的方法之一,而且你可以得到响应。


11
有时候curl并未启用,这时你需要用传统的方式完成。 - Benjamin Eckstein

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接