欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-03-13 10:23:15
在android/java平台上实现post一个json数据: jsonobject jsonobj = new jsonobject(); jsonobj.p...

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

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