预览模式: 普通 | 列表

PHP CURL使用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 http_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. $url = "http://www.baidu.com"; //请求地址  
  26. $arr = array('a' => 1, 'b' => 2, 'c' => 2); //请求参数(数组)  
  27. $jsonStr = json_encode($arr); //转换为json格式  
  28. $result = http_post_json($url$jsonStr);  
  29. print_r($result);  

Tags: php

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

 广告位

↑返回顶部↑