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画图实例

php画图实例

本文实例讲述了php画图的方法。分享给大家供大家参考。具体实现方法如下: 复制代码 代码如下:<?php  // by MoreWindows $imgWid...

优化php效率,提高php性能的一些方法

1、在可以用file_get_contents替代file、fopen、feof、fgets等系列方法的情况下,尽量用 file_get_contents,因为他的效率高得多!但是要注意...

PHP数组遍历的几种常见方式总结

本文实例讲述了PHP数组遍历的几种常见方式。分享给大家供大家参考,具体如下: 1、使用for循环遍历数组 conut($arr);用于统计数组元素的个数。 for循环只能用于遍历,纯索引...

php简单的上传类分享

本文实例为大家分享了php上传类,供大家参考,具体内容如下 <?php class UploadFile{ var $inputName; //控件...

PHP下使用CURL方式POST数据至API接口的代码

其实,也比较简单,上代码:复制代码 代码如下:<?php          $url = 'http...