如何POST一个JSON格式的数据给Restful服务

分类:WebAndroidPHPrestful 14491人阅读 评论(6) 收藏 举报 post json restful php jquery

在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(){
...
}
})

<span style="font-family: Arial; background-color: rgb(255, 255, 255);"></span>
<span style="font-family: Arial; background-color: rgb(255, 255, 255);"></span>
   


<span style="font-family: Arial; background-color: rgb(255, 255, 255);">PHP用cUrl实现:</span>

[php] view plain copy
  1. $data=array("name"=>"Hagrid","age"=>"36");
  2. $data_string=json_encode($data);
  3. $ch=curl_init('http://api.local/rest/users');
  4. curl_setopt($ch,CURLOPT_CUSTOMREQUEST,"POST");
  5. curl_setopt($ch,CURLOPT_POSTFIELDS,$data_string);
  6. curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
  7. curl_setopt($ch,CURLOPT_HTTPHEADER,array(
  8. 'Content-Type:application/json',
  9. 'Content-Length:'.strlen($data_string))
  10. );
  11. $result=curl_exec($ch);


by iefreer


更多相关文章

  1. Android多种数据库存储方式对比
  2. 基于TCP/IP协议的Java服务端与Android客户端的Socket通信及数据
  3. [Android1.6]继承BaseAdapter为GridView设置数据时设置setLayout
  4. Android中Bundle支持的数据类型
  5. Android 中的MVC与数据流动
  6. Android 通过代码实现控制数据网络的开关(仅适用于5.0以上)
  7. 20172323 2017-2018-2《程序设计与数据结构》第十一周学习总结
  8. Android多文件断点续传(二)——实现数据库储存下载信息

随机推荐

  1. activity配置信息详解
  2. Android(安卓)Camera2 Hal3(一)初始化
  3. Android(安卓)Studio多渠道打包和代码混
  4. Android(安卓)RecyclerView嵌套RecyclerV
  5. Cursor, MergeCursor, MatrixCursor灵活
  6. android之recyclerview的基本使用
  7. android sqlite database is locked (cod
  8. Android(安卓)FrameWork——Binder机制详
  9. 仿微信底部Tab切换,TabHost+Fragment的用
  10. Android(安卓)开发艺术探索笔记(十三) 之 W