修复Guzzle 400错误的API请求

问题描述 投票:0回答:1

我试图使用Guzzle将AJAX API请求脚本转换为php,但是我一直收到“400 Bad Request”错误。 Ajax版本运行正常。但我正在尝试在后端自动化该过程。该脚本通过“POST”请求将文件发送到远程API,并且意味着返回一个JSON对象,然后将其保存到文件中。

我发现(google)的大多数可能的解决方案涉及做一些异常处理或直接停用guzzle错误。这些都没有奏效。我知道凭据都是正确的,因为我使用错误的凭据进行了测试,并且它返回了授权错误。

这个AJAX代码工作正常,它从html表单获取文件并将其上传到API服务器。


            $('#btnUploadFile').on('click', function () { 
                var data = new FormData();
                var files = $("#fileUpload").get(0).files; 
                for (var i = 0; i < files.length; i++) { 
                data.append("audioFiles", files[i]); } 
                data.append("scoresTypes", JSON.stringify([46, 47])); 
                data.append("Flavor", 1);
                data.append("AgentUsername", '[email protected]');
                var ajaxRequest = $.ajax({ type: "POST", url: 'https://remoteserver.com/api/', 
                headers: { 'Authorization': 'Basic ' + btoa('username' + ':' + 'password') },
                scoresTypes: "",
                contentType: false,
                processData: false,
                data: data,


                success: function (data) { $("#response").html(JSON.stringify(data)); } }); 

                ajaxRequest.done(function (xhr, textStatus) {  }); 

                }); 
            }); 

这是将错误“400 Bad Request”返回给文件的PHP代码

public function sendFile($file_path, $file_name){

        $client               = new Client();
        $url                  = 'https://remoteserver.com/api/';
        $credentials          = base64_encode('username:password');
        $audio                = fopen($file_path, 'r');
        $data                 = [];
        $data['audioFiles']    = $audio;
        $data['scoresTypes']   = json_encode([46, 47]);
        $data['Flavor']        = 1;
        $data['AgentUsername'] = '[email protected]';
        $json_file             = '/path/'.$file_name.'.json';

        try{
            $response = $client->request('POST', $url, [
                'headers' => [
                    'Authorization' => 'Basic '.$credentials,
                 ],
                'scoresTypes' => '',
                'contentType' => 'false',
                'processData' => false,
                'data'=>$data
            ]);
            $response_s = json_encode($response);
        }
        catch(RequestException $e) {
            $response_s = $e->getResponse()->getBody();
        }

        Storage::disk('disk_name')->put($json_file, $response_s);

所以这是PHP函数保存到文件而不是预期的JSON对象的输出。

{"code":14,"message":"There are no values in scoresTypes or JobTypes keys, please insert valid values in one, or both of them.","responseStatusCode":400}

但正如您所看到的,提供给ajax版本的初始数据似乎与我在php请求中发送的数据相同。

php laravel api cross-domain guzzle
1个回答
0
投票

你有没有尝试将Content-Type设置为multipart / form-data,因为你发送文件,我认为post请求的默认标题是application / x-www-form-urlencoded我不是一个guzzle专家但是从我看到的在这里的示例中,您可以使用类似的东西

http://docs.guzzlephp.org/en/latest/quickstart.html?highlight=file#sending-form-files

<?php 
$response = $client->request('POST', 'http://httpbin.org/post', [
    'multipart' => [
        [
            'name'     => 'field_name',
            'contents' => 'abc'
        ],
        [
            'name'     => 'file_name',
            'contents' => fopen('/path/to/file', 'r')
        ],
        [
            'name'     => 'other_file',
            'contents' => 'hello',
            'filename' => 'filename.txt',
            'headers'  => [
                'X-Foo' => 'this is an extra header to include'
            ]
        ]
    ]
]);
© www.soinside.com 2019 - 2024. All rights reserved.