使用Guzzle获取403测试API

时间:2019-03-11 19:07:16

标签: php rest symfony guzzle6

我正在用symfony 4编写一个api,因此为了测试它,我安装了Guzzle发出一些请求。 我有一个本地Web服务器(与php完全相同-或与symfony的控制台一起运行的服务器很重要)。

我的代码如下:

<?php

require __DIR__.'/vendor/autoload.php';

use GuzzleHttp\Psr7\Request;

$client = new \GuzzleHttp\Client([
    'base_uri' => 'http://127.0.0.1:8000',
    'http_errors' => false,
]);

$response = $client->get('/');

echo $response->getStatusCode();    // --> 403

或者如果我用'http_errors'=> false注释该行,则会得到:

PHP Fatal error:  Uncaught GuzzleHttp\Exception\ClientException: Client error: `GET http://127.0.0.1:8000/` resulted in a `403 Forbidden` response:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html><head>
<meta http-equiv (truncated...)
 in D:\Work\Programming\SIGMET\2.0\sigmet_2.0\vendor\guzzlehttp\guzzle\src\Exception\RequestException.php:113
Stack trace:
#0 D:\Work\Programming\SIGMET\2.0\sigmet_2.0\vendor\guzzlehttp\guzzle\src\Middleware.php(66): GuzzleHttp\Exception\RequestException::create(Object(GuzzleHttp\Psr7\Request), Object(GuzzleHttp\Psr7\Response))
#1 D:\Work\Programming\SIGMET\2.0\sigmet_2.0\vendor\guzzlehttp\promises\src\Promise.php(203): GuzzleHttp\Middleware::GuzzleHttp\{closure}(Object(GuzzleHttp\Psr7\Response))
#2 D:\Work\Programming\SIGMET\2.0\sigmet_2.0\vendor\guzzlehttp\promises\src\Promise.php(156): GuzzleHttp\Promise\Promise::callHandler(1, Object(GuzzleHttp\Psr7\Response), Array)
#3 D:\Work\Programming\SIGMET\2.0\sigmet_2.0\vendor\guzzlehttp\promises\src\Ta in D:\Work\Programming\SIGMET\2.0\sigmet_2.0\vendor\guzzlehttp\guzzle\src\Exception\RequestException.php on line 113

那会是什么? 预先感谢。

1 个答案:

答案 0 :(得分:0)

我发现问题出在定义代理设置的环境变量上