使用Google Drive多部分上传API时遭遇JSON解析错误(400)的问题求助
Google Drive多部分上传API时遭遇JSON解析错误(400)的问题求助
我正尝试按照Google Drive多部分上传API的说明上传文件,但一直收到400解析错误,已经折腾一周了还是没解决,求大家帮忙看看!
我添加的请求头如下:
Content-Type : multipart/related; boundary=foo_bar_baz Content-Length : calculated later Authorization : token
请求体内容是:
--foo_bar_baz\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n{"name": "testname.txt","mimeType":"text/plain"}\r\n--foo_bar_baz\r\nContent-Type:text/plain\r\n\r\n1234142 test\r\n--foo_bar_baz--
但Google Drive始终返回以下错误响应:
{ "error": { "code": 400, "message": "Invalid JSON payload received. Unable to parse number.\n--foo_bar_baz\\r\\nCon\n^", "errors": [ { "message": "Invalid JSON payload received. Unable to parse number.\n--foo_bar_baz\\r\\nCon\n^", "domain": "global", "reason": "parseError" } ], "status": "INVALID_ARGUMENT" } }
我用WordPress的PHP函数编写的实际代码如下:
public function create_file2($file_name, $mime_type, $file_content, $parent) { $params = [ 'uploadType' => 'multipart', 'supportsAllDrives' => 'true', 'includeItemsFromAllDrives' => 'true' ]; $metadata = [ 'name' => $file_name, 'mimeType' => $mime_type ]; // Füge parent hinzu, wenn vorhanden if (!empty($parent)) { $metadata['parents'] = [$parent]; } $metadata_json = json_encode($metadata, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); $boundary = md5(time()); $multipart_content = "--$boundary\r\n"; $multipart_content .= "Content-Type: application/json; charset=UTF-8\r\n"; $multipart_content .= "\r\n" . $metadata_json . "\r\n"; $multipart_content .= "--" . $boundary . "\r\n"; $multipart_content .= "Content-Type: $mime_type\r\n"; $multipart_content .= "Content-Transfer-Encoding: base64\r\n"; $multipart_content .= "\r\n" . base64_encode($file_content) . "\r\n"; $multipart_content .= "--$boundary--\r\n"; $url = KPR_gdrive_api_endpoint_files . '?' . http_build_query($params); $response = wp_remote_post($url, [ 'method' => 'POST', 'headers' => [ 'Authorization' => 'Bearer ' . json_decode($this->token, true)['access_token'], 'Content-Type' => 'multipart/related; boundary=' . $boundary, 'Content-Length' => strlen($multipart_content) ], 'body' => $multipart_content, 'timeout' => 60 ]); if (is_wp_error($response)) { error_log('create_file2 error: ' . $response->get_error_message()); return false; } $response_body = json_decode(wp_remote_retrieve_body($response), true); if (isset($response_body['id'])) { return $response_body['id']; } error_log('create_file2 error: Unexpected response'); }
不管我怎么调整请求体的格式,返回的错误都是一样的,实在找不到问题出在哪了,有没有大佬能帮我排查一下?
备注:内容来源于stack exchange,提问作者MZR
相关产品推荐
相关产品推荐

