使用PHP Curl调用Omeka API发送JSON时遇400及403错误求助
PHP Curl请求Omeka REST API返回400 Bad Request,测试接口返回403 Forbidden
我无法通过PHP Curl成功向Omeka REST API发送POST请求,需传递一个复杂JSON对象。该JSON通过Postman发送至指定接口时完全正常,但我的PHP代码执行后返回400 Bad Request。根据Omeka API文档,该错误可能源于无效GET参数、请求体非JSON对象或保存记录失败。调整请求头后,移除任一头部会出现403 Forbidden错误。
为排查问题,我创建了测试接口:test.php通过Curl请求what.php时返回403 Forbidden,但直接用Postman请求what.php则返回200 OK。我无法理解该403错误的原因,恳请帮助!
相关代码
向Omeka API请求的PHP代码
<?php $data = array ( /* 此处为我的数组格式数据 */ ); // 验证:保存为JSON文件后用Postman测试正常 $fp = fopen('results_'.time().'.json', 'w'); fwrite($fp, json_encode($data, JSON_UNESCAPED_SLASHES)); fclose($fp); // Curl请求部分 $url = 'https://omeka.url.ltd/api/items?key=xxxxxxxxxxxxxxx'; $payload = json_encode($data, JSON_UNESCAPED_SLASHES); $length = strlen($payload); $ch = curl_init($url); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_HTTPHEADER, array( "Content-Type:application/json", "Content-Length:".$length, "Host:https://www.geopolitique.net", "User-Agent:PostmanRuntime/7.32.2") ); curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $result = curl_exec($ch); echo $result; curl_close($ch); ?>
测试用test.php代码
<?php // 要发送POST请求的URL $url = 'https://api.domain.ltd/what.php'; // 要发送的POST数据 $fields = [ 'key1' => 'value1', 'key2' => 'value2', ]; // 格式化POST数据 $fields_string = http_build_query($fields); // 初始化Curl $ch = curl_init(); // 设置URL、POST参数和数据 curl_setopt($ch,CURLOPT_URL, $url); curl_setopt($ch,CURLOPT_POST, true); curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string); // 设置返回结果不直接输出 curl_setopt($ch,CURLOPT_RETURNTRANSFER, true); // 执行请求 $result = curl_exec($ch); echo "results:\n".$result; ?>
测试用what.php代码
<?php $data = array_merge(apache_request_headers(), $_POST, $_SERVER); // 将请求数据保存为JSON文件 $fp = fopen('request_'.time().'.json', 'w'); fwrite($fp, json_encode($data, JSON_UNESCAPED_SLASHES)); fclose($fp); ?>
内容的提问来源于stack exchange,提问作者Jeremy
相关产品推荐
相关产品推荐

