当前位置:首页 > PHP教程 > PHP高级教程

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

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

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


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!