[英]Fixing the Guzzle 400 Bad request for an API error
I tried to convert an AJAX API request script into php using Guzzle, however I keep getting a '400 Bad Request' error. 我试图使用Guzzle将AJAX API请求脚本转换为php,但是我不断收到“ 400 Bad Request”错误。 The Ajax version works fine.But I'm trying to automate the process in the back end.
Ajax版本工作正常。但是我试图在后端自动化该过程。 The script sends a file to the remote API via a 'POST' request and is meant to return a JSON object back which I then save it to a file.
该脚本通过“ POST”请求将文件发送到远程API,并打算返回一个JSON对象,然后我将其保存到文件中。
Most of the possible solutions I found(googled for) involved either doing some exception handling or straight deactivating the guzzle errors. 我发现(谷歌搜索)的大多数可能解决方案都涉及执行一些异常处理或直接停用耗时错误。 None of which worked.
没有一个工作。 I know that the credentials are all correct because I tested with wrong credentials and it returned an authorization error.
我知道凭据都是正确的,因为我使用错误的凭据进行了测试,并且返回了授权错误。
This AJAX code works fine, it gets a file from an html form and uploads it to the API server. 此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) { });
});
});
This is the PHP code that returns the error '400 Bad Request' to the file 这是将错误“ 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);
So this is the output that the PHP function is saving to the file instead of the expected JSON object. 因此,这是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}
But as you can see the initial data provided to the ajax version seems to be the same as the one I send in the php request. 但是正如您所看到的,提供给ajax版本的初始数据似乎与我在php请求中发送的数据相同。
have you tried setting the Content-Type to multipart/form-data since you are sending files, i think the default header for post request is application/x-www-form-urlencoded I'm not a guzzle expert but from what i saw on the examples here you can use something like this instead 您是否尝试过将Content-Type设置为multipart / form-data,因为您正在发送文件,所以我认为发布请求的默认标头是application / x-www-form-urlencoded我不是一个吃惊的专家,但从我的观察在这里的示例中,您可以使用类似这样的内容
http://docs.guzzlephp.org/en/latest/quickstart.html?highlight=file#sending-form-files 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.