【问题标题】:Replicate CURL multipart/form-data request with Guzzle / League OAuth2 Client使用 Guzzle / League OAuth2 客户端复制 CURL 多部分/表单数据请求
【发布时间】:2019-11-06 18:22:55
【问题描述】:

我正在尝试在 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 库来发送请求。我正在寻找这两个请求之间的任何差异或有关如何自己进一步解决此问题的信息,因为我整天都在旋转我的车轮。非常感谢

【问题讨论】:

    标签: oauth-2.0 guzzle


    【解决方案1】:

    thephpleague/oauth2-client 使用不同的 Provider 来创建请求,这些 Provider 实现 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 只允许使用“headers”、“body”和“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 );
    

    参考

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-19
      • 2018-09-08
      • 1970-01-01
      • 1970-01-01
      • 2015-05-11
      • 2020-11-28
      • 2017-07-29
      • 2021-12-12
      相关资源
      最近更新 更多