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); 

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

相关文章

PHP 木马攻击防御技巧

1、防止跳出web目录 首先修改httpd.conf,如果你只允许你的php脚本程序在web目录里操作,还可以修改httpd.conf文件限制php的操作路径。比如你的web目录是/us...

php下通过IP获取地理位置的代码(小偷程序)

复制代码 代码如下: function get_ip_place() { $ip=file_get_contents("http://fw.qq.com/ipaddress"); $ip...

PHP return语句另类用法不止是在函数中

分享下PHP return语句的另一个作用,在bbPress的代码中看到的一个奇葩使用方法。 一直以为,return只能出现在函数中,直到看了bbPress的代码: <?...

上传文件先创建目录 再上传到目录里面去

1,表单部分: 复制代码 代码如下: <html> <head> <title> my is upfile app!! </title>...

smarty中先strip_tags过滤html标签后truncate截取文章运用

strip_tags() 函数剥去 HTML、XML 以及 PHP 的标签。 复制代码 代码如下: <?php echo strip_tags(“Hello <b>wo...