[英]Fixing the Guzzle 400 Bad request for an API error
我试图使用Guzzle将AJAX API请求脚本转换为php,但是我不断收到“ 400 Bad Request”错误。 Ajax版本工作正常。但是我试图在后端自动化该过程。 该脚本通过“ POST”请求将文件发送到远程API,并打算返回一个JSON对象,然后我将其保存到文件中。
我发现(谷歌搜索)的大多数可能解决方案都涉及执行一些异常处理或直接停用耗时错误。 没有一个工作。 我知道凭据都是正确的,因为我使用错误的凭据进行了测试,并且返回了授权错误。
此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", 'person@email.com');
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'] = 'person@email.com';
$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请求中发送的数据相同。
您是否尝试过将Content-Type设置为multipart / form-data,因为您正在发送文件,所以我认为发布请求的默认标头是application / x-www-form-urlencoded我不是一个吃惊的专家,但从我的观察在这里的示例中,您可以使用类似这样的内容
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'
]
]
]
]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.