预览模式: 普通 | 列表

PHP通过Http Post请求发送Json对象数据

PHP调用第三方Java/.Net写好的 Restful Api,其中有些接口,需要在发送 POST请求时,传入对象。
 
Http中传输对象,最好的表现形式莫过于JSON字符串了,但是作为参数的接收方,又是需要被告知传过来的是JSON!
 
只要发送一个http Content-Type头信息即可,即 “Content-Type: application/json; charset=utf-8”,参考代码如下:
PHP代码
  1. /** 
  2.  * PHP发送Json对象数据 
  3.  * @param $url 请求url 
  4.  * @param $jsonStr 发送的json字符串 
  5.  * @return array 
  6.  */  
  7. function send_post_json($url$jsonStr)  
  8. {  
  9.     $ch = curl_init();  
  10.     curl_setopt($ch, CURLOPT_POST, 1);  
  11.     curl_setopt($ch, CURLOPT_URL, $url);  
  12.     curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);  
  13.     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  
  14.     curl_setopt($ch, CURLOPT_HTTPHEADER, array(  
  15.             'Content-Type: application/json; charset=utf-8',  
  16.             'Content-Length: ' . strlen($jsonStr)  
  17.         )  
  18.     );  
  19.     $response = curl_exec($ch);  
  20.     $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);  
  21.     curl_close($ch);  
  22.     return array($httpCode$response);  
  23. }  
  24.    
  25. $target = "http://texst.api.cn/api/dev/start";  
  26.    
  27. $postdata=array();  
  28. $postdata["token"]="99d710a1f7bc11eab31a00508c";  
  29. $postdata["imei"]="868739053737";  
  30. $jsonStr = json_encode($postdata);  
  31. $result = send_post_json($target,$jsonStr);  
  32. var_dump($result);  
  33.    
  34. //Json字符串转换成类对象 即可  
 

Tags: php

分类:技术文章 | 固定链接 | 评论: 0 | 引用: 0 | 查看次数: 159

PHP如何接收post传递的json数据

PHP如何接收post来的json数据?

要在PHP中整体接收POST数据,有两种方法。

注意,要使用以下两种方法,Content-Type不能为multipart/form-data。

方法一:

使用:file_get_contents('php://input')

查看更多...

Tags: php

分类:技术文章 | 固定链接 | 评论: 0 | 引用: 0 | 查看次数: 155

 广告位

↑返回顶部↑