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 gbk环境下json_dencode传送来的汉字

复制代码 代码如下: function ArrEncode($arr){ foreach($arr as $k=>$v){ if(is_array($v)){ $arr[$k] =...

async和DOM Script文件加载比较

async和DOM Script文件加载比较

目前我用demo.js作为执行文件操作.代码: var now = function() { return +(new Date()); } var t_s = now(); whi...

$_GET['goods_id']+0 的使用详解

目的: 为了防止sql注入,tid,goods_id都是正整数类型,防止人为了在后面追加 ?tid=1 or 1 这样的语句.原理: 不管你的参数多么险恶,+0后都老老实实变成数值类型...

PHP简单判断iPhone、iPad、Android及PC设备的方法

本文实例讲述了PHP简单判断iPhone、iPad、Android及PC设备的方法。分享给大家供大家参考,具体如下: 因为工作需要我们需要知道是什么样了用户访问了我网站了,现在的移动设备...

PHP实现大数(浮点数)取余的方法

本文实例讲述了PHP实现大数(浮点数)取余的方法。分享给大家供大家参考,具体如下: 一般我们进行取余运算第一个想到的就是用百分号%,但当除数是个很大的数值,超出了int范围时,这样取余就...