我想使用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
如何根据上述cURL选项获取JSON?
答案 0 :(得分:1)
为什么在使用cookiefile和cookiejar时手动设置cookie标头?这不应该是必需的。
您收到setcookie标头也很可疑,可能服务器不接受您发送的会话cookie。
另外,为什么不在第二个请求中忽略无效的SSL?
最后,为什么不在第二个请求上发送相同的用户代理?
我想如果你解决了这些问题,你会看到预期的行为。