Guzzle编码主体Json,但我想要表单数据


Guzzle encodes body to Json, but I want form data

我正试图发布一些东西到Googles oAuth server做一些认证。Google确实想要表单数据(Content-Type: application/x-www-form-urlencoded)中的这些信息,但我的客户端似乎坚持(据我所知)让主体JSON。我正在使用Guzzle 4.*

我已经将我的URL更改为PostCatcher.io url,所以我可以看到输出的内容(因为对于我的生命,我无法弄清楚如何看到实际的原始HTTP请求喷吐出来),看起来好像有JSON出来。

我的代码(我现在使用一个测试url):

$client = new GuzzleClient();
$url = "https://www.googleapis.com/" . "oauth2/v3/token";
$test_url = 'http://postcatcher.in/catchers/55602457b92ce203000032ae';
$request = $client->createRequest('POST', $test_url);
$request->setHeader('Content-Type', 'application/x-www-form-urlencoded'); //should be redundant
$body = $request->getBody();
$body->setField('code', $code);
$body->setField('client_id', $this->client_id);
$body->setField('client_secret', $this->client_secret);
$body->setField('redirect_url', $this->redicrect_url);
$body->setField('grant_type', $this->grant_type);
try {
    $response = $client->send($request);
    $result = $response->getBody();
    return $result;
} catch ('Exception $exc) {
    return $exc->getCode() . ' ' . $exc->getMessage();
}

文档说这应该足够了。我错过了什么?

使用Guzzle 5.2我做了同样的事情:

$request = $this->createRequest(
    $method,
    $uri,
    ['body' => $php_array_of_values ]
);
$response = $this->send($request);

我找到问题了。我确实升级到了Guzzle 5。*虽然我怀疑这不是真正的解决方案。

我只需要看看响应内容。因此,在调用的异常子句中,我添加了:

if ($exc->hasResponse()) {
   return $exc->getResponse()->json();
}

这给了我一个明确的错误信息从谷歌。错误信息为"缺少参数:redirect_uri"。这是因为我把uri写成了url