我想使用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的输出。我刚刚从其他来源利用它.. –