php http json,PHP如何通过Http Post请求发送Json对象数据?

因项目的需要,PHP调用第三方 Java/.Net 写好的 Restful Api,其中有些接口,需要 在发送 POST 请求时,传入对象。

Http中传输对象,最好的表现形式莫过于JSON字符串了,但是作为参数的接收方,又是需要被告知传过来的是JSON!

其实这不难,只需要发送一个 http Content-Type头信息即可,即 “Content-Type: application/json; charset=utf-8”,参考代码如下:

01

02

/**

03

* PHP发送Json对象数据

04

*

05

* @param $url 请求url

06

* @param $jsonStr 发送的json字符串

07

08

*/

09

function http_post_json($url, $jsonStr)

10

{

11

$ch = curl_init();

12

curl_setopt($ch, CURLOPT_POST, 1);

13

curl_setopt($ch, CURLOPT_URL, $url);

14

curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);

15

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

16

curl_setopt($ch, CURLOPT_HTTPHEADER, array(

17

'Content-Type: application/json; charset=utf-8',

18

'Content-Length: ' . strlen($jsonStr)

19

)

20

);

21

$response = curl_exec($ch);

22

$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

23

curl_close($ch);

24

25

return array($httpCode, $response);

26

}

27

28

$url = "http://blog.snsgou.com";

29

$jsonStr = json_encode(array('a' => 1, 'b' => 2, 'c' => 2));

30

list($returnCode, $returnContent) = http_post_json($url, $jsonStr);

API服务端端接收客户端传过来的 “Content-Type: application/json; charset=utf-8”头信息后,再将 http body 数据(即 Json字符串)转换成 类对象!

上一篇:Maven入门教程2:Ma

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用 PHP 的 cURL 库来发送 POST 请求JSON 数据。以下是一个示例代码: ```php $url = 'http://example.com/api'; // API 的 URL $data = array('name' => 'John', 'age' => 30); // 要发送JSON 数据 $ch = curl_init($url); // 初始化 cURL curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 设置返回结果为字符串 curl_setopt($ch, CURLOPT_POST, true); // 设置请求POST curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); // 设置 POST 数据JSON 格式 curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); // 设置请求头中的 Content-Type 为 JSON $response = curl_exec($ch); // 发送请求并获取响应 curl_close($ch); // 关闭 cURL if ($response === false) { // 请求失败 echo 'Error: ' . curl_error($ch); } else { // 请求成功 echo $response; } ``` 在上面的代码中,我们使用了 `curl_setopt()` 函数来设置 cURL 的选项,其中: - `CURLOPT_RETURNTRANSFER`:设置为 `true`,表示将结果返回为字符串,而不是直接输出到页面上。 - `CURLOPT_POST`:设置为 `true`,表示这是一个 POST 请求。 - `CURLOPT_POSTFIELDS`:设置 POST 数据,使用 `json_encode()` 函数将数组转换为 JSON 格式的字符串。 - `CURLOPT_HTTPHEADER`:设置请求头中的 Content-Type 为 application/json,告诉服务器我们发送的是 JSON 数据。 最后,使用 `curl_exec()` 函数发送请求并获取响应,然后使用 `curl_close()` 函数关闭 cURL。如果请求失败,可以使用 `curl_error()` 函数获取错误信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值