我正在尝试在Guzzle中复制CURL POST请求,但是Guzzle请求失败。
这是成功运行的CURL请求:
$file = new \CURLFile( $document );
$file->setPostFilename( basename( $document ) );
$ch = curl_init();
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $ch, CURLOPT_URL, $endpoint );
curl_setopt( $ch, CURLOPT_HTTPHEADER, [
"Authorization: Bearer " . $accessToken,
"Content-Type: multipart/form-data",
] );
curl_setopt( $ch, CURLOPT_POSTFIELDS, [ 'fileData' => $file ] );
$response = curl_exec( $ch );
这是我当前用于Guzzle请求的内容,但它不起作用:
$options['multipart'][] = [
'name' => 'fileData',
'contents' => fopen( $document, 'r' ),
'filename' => basename( $document ),
];
$request = $provider->getAuthenticatedRequest( 'POST', $endpoint, $accessToken, $options );
$response = $provider->getParsedResponse( $request );
Guzzle请求的响应如下:
{"message":"File cannot be empty","errors":[{"code":"Missing","fields":["document"]}]}
值得注意的是,我正在使用thephpleague/oauth2-client库发送请求。我正在寻找两个请求之间的任何差异,或者寻找有关如何自己进一步解决此问题的信息,因为我整天都在为此忙碌。非常感谢
答案 0 :(得分:0)
thephpleague / oauth2-client 使用不同的提供程序来创建请求,这些提供程序实现AbstractProvider
AbstractProvider 's getAuthenticatedRequest()的参数 $ options 与GuzzleHttp\Client 's request()不同:
/**
* Returns an authenticated PSR-7 request instance.
...
* @param array $options Any of "headers", "body", and "protocolVersion".
* @return RequestInterface
*/
public function getAuthenticatedRequest($method, $url, $token, array $options = [])
$ options 所允许的键只有“标题”,“正文”和“ protocolVersion”。
您应该付出额外的努力,并创建所需的标题和正文:
$file = new \CURLFile( $document );
$file->setPostFilename( basename( $document ) );
$data = array(
'uploaded_file' => $file
);
$options = array(
'headers' => array("Content-Type" => "multipart/form-data"),
'body' => $data
);
$request = $provider->getAuthenticatedRequest( 'POST', $endpoint, $accessToken, $options );
参考