将 DELETE curl 方法与 Guzzle 和 sendgrid 一起使用时返回错误请求

Bad request returned when using the DELETE curl method with Guzzle and sendgrid

我正在尝试使用 sendgrid v3 API to purge bounces,在 CLI 中使用 CURL 时它工作正常,这里是命令:

curl -v -X DELETE -d '{"delete_all": true}' -H "Content-Type: application/json" -H "Authorization: Bearer SG.mykey" "https://api.sendgrid.com/v3/suppression/bounces"

但是当尝试使用 Symfony2 / Guzzle 启动它时,我收到了错误的请求错误,但是请求似乎没问题,这里是 (string) $request:

的输出
"""
DELETE /v3/suppression/bounces HTTP/1.1\r\n
Host: api.sendgrid.com\r\n
Authorization: Bearer SG.mykey\r\n
User-Agent: Guzzle/3.9.3 curl/7.35.0 PHP/5.5.9-1ubuntu4.17\r\n
Accept: application/json\r\n
Content-Length: 20\r\n
\r\n
{"delete_all": true}
"""

例外情况:

[Guzzle\Http\Exception\ClientErrorResponseException]   
Client error response                                  
[status code] 400                                      
[reason phrase] BAD REQUEST                            
[url] https://api.sendgrid.com/v3/suppression/bounces

当使用 GET 方法时,它工作正常并且它 returns 我所有的弹跳。

这里是guzzle代码:

$request = $this->httpClient->delete('/v3/suppression/bounces', null, '{"delete_all": true}');
$response = $request->send();

http 客户端是使用 https://api.sendgrid.com 基 URL 初始化的服务。

我认为你的问题是当它只有两个时你发送了 3 个参数来删除,而不是你需要做的是在选项数组中传递正文。

$response = $this->httpClient->delete(
        '/v3/suppression/bounces',
        [
            'body' => json_encode(['delete_all', true]),
            'Authorization' => 'Basic ' . base64_encode($username . ':' . $password),
            'content-type'  => 'application/json'
        ]
    );

Guzzle options docs

回答我自己。问题很明显:content-type header 没有设置,"accept" 设置了。我不关心这个header,因为你在为这个API使用GET方法时不必传递它。所以现在在调试我的请求时 object 我有:

"""
DELETE /v3/suppression/bounces HTTP/1.1\r\n
Host: api.sendgrid.com\r\n
Authorization: Bearer SG.mykey\r\n
Content-Type: application/json\r\n
Content-Length: 20\r\n
User-Agent: Guzzle/3.9.3 curl/7.35.0 PHP/5.5.9-1ubuntu4.17\r\n
Accept: application/json\r\n
\r\n
{"delete_all": true}
"""