【问题标题】:How to do a GET request on PHP using CURL如何使用 CURL 在 PHP 上执行 GET 请求
【发布时间】:2016-11-19 02:45:43
【问题描述】:

我有一个简单的 GET 请求,我正在尝试发出并返回结果。我已经在没有任何标题或正文的 Postman 中尝试过它,它工作得很好。我什至把它放在我的浏览器中,它返回了一个很好的结果。但是,当我在 PHP 中执行此操作时,我什么也得不到。这就是我的代码的样子。我做错了什么?

        $curl = curl_init();

        curl_setopt($curl,CURLOPT_URL,'http://********/vizportal/api/web/v1/auth/kerberosLogin');
        curl_setopt($curl,CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_POST, 0);
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, '20');

        $resp = curl_exec($curl);

        echo $resp;

【问题讨论】:

  • 你只是假设没有失败。 curl_exec 在失败时返回布尔值 false,这将作为零长度字符串回显。试试if ($resp === false) { die(curl_error($curl)); }
  • 我得到了一个空无的回声,我期待一个简单的 JSON 响应。
  • 尝试在末尾添加var_dump(curl_error($curl));,看看是否有任何收获。另外,你为什么将超时作为字符串传递?
  • 我从转储中得到“string(0)”“”。我已经尝试过将超时作为一个数字,但这也不起作用(我看到将它作为一个字符串放在网上的某个地方,这对我来说也没有意义)

标签: php curl get http-get


【解决方案1】:

使用此标头将像浏览器一样的标头发送到服务器:

$curl = curl_init('http://********/vizportal/api/web/v1/auth/kerberosLogin');
curl_setopt($curl, CURLOPT_POST, 0);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, '20');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
//        curl_setopt($curl, CURLOPT_HEADER, true);
//        curl_setopt($curl, CURLINFO_HEADER_OUT, true); // enable tracking

curl_setopt($curl, CURLOPT_HTTPHEADER, array(
    'Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'Accept-Encoding:gzip, deflate, sdch',
    'Accept-Language:en-US,en;q=0.6',
    'Cache-Control:max-age=0',
    'Connection:keep-alive',
    'Host:www.********.tld ', // for example : www.google.com
    'Referer: http://********/vizportal/api/web/v1/auth/kerberosLogin',
    'Upgrade-Insecure-Requests:1',
    'User-Agent:Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36',
));

$response = curl_exec($curl);
curl_close($curl);

【讨论】:

  • 我无法让它工作。虽然,我现在收到此错误:HTTP/1.0 302 Found Location: https://********/vizportal/api/web/v1/auth/kerberosLogin 服务器:BigIP Connection: Keep-Alive Content-Length : 0
  • 301 错误意味着“永久移动”,您应该从响应标头重定向到返回位置 [位置:redirec-location.com/path/] - 将 curl 请求发送到新位置 - 查看响应标头只需启用跟踪 [comment end of此行]
猜你喜欢
  • 2017-08-30
  • 1970-01-01
  • 2018-03-30
  • 2015-07-22
  • 1970-01-01
  • 1970-01-01
  • 2012-11-26
  • 2012-04-11
  • 2017-04-14
相关资源
最近更新 更多