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 显示指定路径下的图片

复制代码 代码如下:function getAllDirAndFile($path) { if(is_file($path)) { if(isImage($path)) { $str="...

PHP实现求连续子数组最大和问题2种解决方法

本文实例讲述了PHP实现求连续子数组最大和问题2种解决方法。分享给大家供大家参考,具体如下: 问题描述 求子数组的最大和 题目描述: 输入一个整形数组,数组里有正数也有负数。 数组中连续...

从php核心代码分析require和include的区别

从php核心代码分析require和include的区别

深入理解PHP之require/include顺序 https://www.jb51.net/article/25867.htm普及在php手册中: require() is ide...

java模拟PHP的pack和unpack类

本文实例为大家分享了java模拟PHP的pack和unpack类的具体代码,供大家参考,具体内容如下 package qghl.intp.util; import java.io...

PHP工厂模式、单例模式与注册树模式实例详解

本文实例讲述了PHP工厂模式、单例模式与注册树模式。分享给大家供大家参考,具体如下: 三种基本设计模式 1、工厂模式:工厂方法或者类生成对象,而不是在代码中直接new 2、单例模式:使...