POST一个JSON格式的数据给Restful服务实例详解

yipeiwu_com6年前PHP代码库

在Android/Java平台上实现POST一个json数据:

JSONObject jsonObj = new JSONObject();
jsonObj.put("username", username);
jsonObj.put("apikey", apikey);
// Create the POST object and add the parameters
HttpPost httpPost = new HttpPost(url);
StringEntity entity = new StringEntity(jsonObj.toString(), HTTP.UTF_8);
entity.setContentType("application/json");
httpPost.setEntity(entity);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(httpPost);

用curl可执行如下命令:

curl -l -H "Content-type: application/json" -X POST -d '{"phone":"13521389587","password":"test"}' http://domain/apis/users.json

用jQuery:

$.ajax({
 url:url,
 type:"POST",
 data:data,
 contentType:"application/json; charset=utf-8",
 dataType:"json",
 success: function(){
  ...
 }
})

PHP用cUrl实现:

$data = array("name" => "Hagrid", "age" => "36");                                   
$data_string = json_encode($data);    
$ch = curl_init('http://api.local/rest/users');    
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");              
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array(          
  'Content-Type: application/json', 
  'Content-Length: ' . strlen($data_string))      
);                                                           
$result = curl_exec($ch); 

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

相关文章

php无序树实现方法

php无序树实现方法

本文实例讲述了php无序树实现方法。分享给大家供大家参考。具体如下: 运行效果如下图所示: php代码如下: <?php /* 用php写的无序树 */ cla...

PHP获取访问页面HTTP状态码的实现代码

方法一 $header_info=get_headers('//www.jb51.net/'); echo $header_info[0]; //耗时 0.67~0.78 方法二...

PHP Stream_*系列函数

PHP Stream_*系列函数

下图是对这个系列函数的思维导图——我也是第一次使用思维导图这种工具。大图在这里。其中stream_socket_*系列是PHP 5新加入的处理socket连接的函数,简单方便,下一篇博客...

网页上facebook分享功能具体实现

复制代码 代码如下: <span style=" font-family: Verdana, Arial, Helvetica, sans-serif; word-wrap: no...

深入了解PHP类Class的概念

例如,一个交通工具可以定义有颜色、轮胎数、制造商、型号和容量等性质,并定义有停止、前进、转弯和鸣笛等行为。在OOP术语中,实体的性质和行为的具体定义称为类(class)。 类的定义与创建...