POST一個JSON格式的數(shù)據(jù)給Restful服務(wù)實例詳解
更新時間:2017年04月07日 14:15:45 投稿:lqh
這篇文章主要介紹了POST一個JSON格式的數(shù)據(jù)給Restful服務(wù)實例詳解的相關(guān)資料,需要的朋友可以參考下
在Android/Java平臺上實現(xiàn)POST一個json數(shù)據(jù):
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可執(zhí)行如下命令:
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實現(xiàn):
$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);
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
基于PHP創(chuàng)建Cookie數(shù)組的詳解
本篇文章是對在PHP中創(chuàng)建Cookie數(shù)組的方法進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-07-07
PHP實現(xiàn)的生成唯一RequestID類完整示例
這篇文章主要介紹了PHP實現(xiàn)的生成唯一RequestID類,結(jié)合完整實例形式分析了php唯一標(biāo)識符生成、session操作等相關(guān)實現(xiàn)與使用技巧,需要的朋友可以參考下2018-07-07
PHP中通過fopen()函數(shù)訪問遠(yuǎn)程文件示例
這篇文章主要介紹了PHP中通過fopen()函數(shù)訪問遠(yuǎn)程文件示例,本文講解了fopen函數(shù)的作用、使用它需要的配置問題、超時問題等內(nèi)容,并給出了代碼實例,需要的朋友可以參考下2014-11-11

