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

yipeiwu_com4年前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 is_subclass_of函数的一个BUG和解决方法

is_subclass_of的作用: 复制代码 代码如下:bool is_subclass_of ( object object, string class_name )如果对象 obj...

php+redis实现消息队列功能示例

本文实例讲述了php+redis实现消息队列功能。分享给大家供大家参考,具体如下: 个人理解在项目中使用消息队列一般是有如下几个原因: 把瞬间服务器的请求处理换成异步处理,缓解服务器的压...

PHP实现数组的笛卡尔积运算示例

本文实例讲述了PHP实现数组的笛卡尔积运算。分享给大家供大家参考,具体如下: 数组的笛卡尔积在实际中还是挺有用处的,比如计算商品的规格时就经常用到,下面写一种实现方式,如下代码 $a...

PHP实现全角字符转为半角方法汇总

最简单的方法 <?php $str = "0123ABCDFWS\",.?<>{}[]*&^%#@!~()+-|:;"; echo "$str"; echo...

PHP实现Soap通讯的方法

本文实例讲述了PHP实现Soap通讯的方法。分享给大家供大家参考。具体实现方法如下: 复制代码 代码如下:<?php function HttpSoap($server,...