我想使用PHP cURL通過REST API檢索JSON數據。使用PHP cURL通過REST API獲取JSON
在這篇文章中使用PHP代碼,我可以用URL繞過Spring Security的頁面:
https://<host>/appserver/j_spring_security_check
然而,JSON這個URL裏面存在,我想取,
https://<host>/appserver/portal/api/1.0/apps
這是我用來自動登錄的PHP代碼,我試過使用file_get_contents(url)
但它失敗了,只有下面的代碼才能確認登錄。
<?php
function login(){
$headers[] = "Accept: */*";
$headers[] = "Connection: Keep-Alive";
$headers[] = "Content-type: application/x-www-form-urlencoded;charset=UTF-8";
$data = "j_username=admin&j_password=demoserver";
$data = rtrim($data, "&");
global $sessionid;
$sessionid = dirname(__FILE__).'/cookie2.txt'
$ch = curl_init();
$options = array(
CURLOPT_REFERER => "https://<host>/appserver/portal/login",
CURLOPT_HTTPHEADER => $headers,
CURLOPT_COOKIEFILE => $sessionid,
CURLOPT_COOKIEJAR => $sessionid,
CURLOPT_URL => "https://<host>/appserver/j_spring_security_check",
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $data,
CURLOPT_HEADER => true,
CURLOPT_USERAGENT => 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:51.0) Gecko/20100101 Firefox/51.0');
curl_setopt_array($ch, $options);
$content = curl_exec($ch);
curl_close($ch);
}
login();
$text = file_get_contents($sessionid);
preg_match('/\w{32}/u', $text, $match);
$jsession = implode($match);
$headers1[] = "Accept: */*";
$headers1[] = "Connection: Keep-Alive";
$headers1[] = "Content-type: application/json";
$headers1[] = "Cookie: JSESSIONID=".$jsession;
$url = 'https://<host>/appserver/portal/api/1.0/apps';
$ch2 = curl_init();
curl_setopt($ch2, CURLOPT_URL, $url);
curl_setopt($ch2, CURLOPT_HTTPHEADER, $headers1);
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch2, CURLOPT_COOKIEFILE, $sessionid);
curl_setopt($ch2, CURLOPT_COOKIEJAR, $sessionid);
curl_setopt($ch2, CURLOPT_HTTPGET, 1);
$result = curl_exec($ch2);
curl_close($ch2);
// var_dump(json_decode($result, true));
$output = json_decode ($result);
這是PHP代碼執行後的結果:
HTTP/1.1 302 Found Date: Fri, 17 Feb 2017 03:59:00 GMT
Server: Apache/2.2.26 (Unix) mod_ssl/2.2.25 OpenSSL/1.0.1e mod_jk/1.2.37
Set-Cookie: JSESSIONID=DB7139F7B8EE30F868A8392A4BF15523; Path=/appserver/; HttpOnly
Location: https://192.168.100.100:444/appserver/portal/welcome
Content-Length: 0
Access-Control-Allow-Origin: *
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/plain
我怎樣才能獲取JSON給出的上述捲曲的選擇嗎?
當你說「結果」時,你的意思是你從'$ result'中檢索到了什麼? –
是的,這是我的代碼中$ result的輸出。我剛剛從其他來源利用它.. –