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

yipeiwu_com5年前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); 

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

相关文章

C#静态方法与非静态方法实例分析

本文实例分析了C#静态方法与非静态方法,并对其用法进行了较为全面的分析。分享给大家供大家参考。具体分析如下: 通常来说,C#的类中可以包含两种方法:静态方法和非静态方法。 使用了stat...

PHP获取数组中单列值的方法

本文实例讲述了PHP获取数组中单列值的方法。分享给大家供大家参考,具体如下: PHP中获取数组中单列的值如下: 利用PHP中的数组函数 array_column():返回数组中某个单列的...

什么是PEAR?什么是PECL?PHP中两个容易混淆的概念解释

概述 关于PEAR,PECL这两个东西,初学PHP的时候就知道,但是貌似用的人很少再加上以前也是在Windows下做开发,所以了解的不多,现在转到Mac了,就把这两个东西彻底弄弄清楚。...

php计算十二星座的函数代码

核心代码: 复制代码 代码如下: <?php /* * 计算星座的函数 string get_zodiac_sign(string month, string day) * 输入:...

PHP网站安装程序制作的原理、步骤、注意事项和示例代码

1.制作PHP安装程序的原理 其实PHP程序的安装原理无非就是将数据库结构和内容导入到相应的数据库中,从这个过程中重新配置连接数据库的参数和文件,为了保证不被别人恶意使用安装文件,当安装...