php - 带有 php curl 的 2ba Web API 发布请求
问题描述
我使用2ba它的 API 来接收我以后想要存储在我的数据库中的产品信息。我正在尝试创建一个发布请求以接收我需要的数据。这是我想要开始工作的请求。这是我的代码:
postApiData.php
<?php
/**
* Posts API data based on given parameters at index.php.
*/
// Base url for all api calls.
$baseURL = 'https://api.2ba.nl';
// Version number and protocol.
$versionAndProtocol = '/1/json/';
// All parts together.
$url = $baseURL . $versionAndProtocol . $endPoint;
// Init session for CURL.
$ch = curl_init();
// Init headers. Security for acces data.
$headers = array();
$headers[] = "Authorization: Bearer " . $token->access_token;
// Options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($parameters));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
// Execute request.
$data = curl_exec($ch);
// If there is an error. Show whats wrong.
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
echo "<br>";
echo "Error location: postApiData";
exit();
}
// Ends the CURL session, frees all resources that belongs to the curl (ch).
curl_close($ch);
// String to array.
$data = json_decode($data);
?>
索引.php
// Specified url endpoint. This comes after the baseUrl.
$endPoint = 'Product/forGLNAndProductcodes';
// Parameters that are required or/and optional for the endPoint its request.
$parameters = [
'gln' => '2220000075756',
'productcodes' => ['84622270']
];
// Get Supplier info
include("postApiData.php");
print_r($data);
exit();
我的 API 密钥确实有效,因为我已经完成了很多不同的GET请求,而且我也没有收到拒绝访问错误。
我使用此代码得到的错误是:请求的 URL 返回错误:500 内部服务器错误当我删除curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($parameters));
部件时,我还收到“错误请求”400 错误
有谁知道我做错了什么?
PS:除非您拥有具有工作密钥等的 2ba 帐户,否则您实际上不可能亲自尝试此代码。
解决方案
好的,我已经修好了...
我不得不添加一些额外的标题并像这样更改 $parameters 值:
postApiData.php
// Added this above the authorization.
$headers[] = "Connection: close";
$headers[] = "Accept-Encoding: gzip,deflate";
$headers[] = "Content-Type: application/json";
// Removed the http_build_query part.
curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters);
索引.php
// Encoded in a json way as asked by 2ba request.
$parameters = json_encode($parameters);
推荐阅读
- javascript - 如何避免 babel 的 'Uncaught ReferenceError: stringClasses is not defined'?
- java - Solr CloudSolrClient :原因:java.lang.ClassCastException:java.lang.String 无法转换为 java.util.Map
- jenkins - Podtemplate() 不接受使用 readFile 或 yamlFile 的 yaml 文件
- javascript - 如何使用 puppeteer 访问 iframe #document?
- python - 在healpy地图中分箱?
- python - 在 start_urls 中分配代理和用户代理
- r - R-plotly中线条颜色的名称是什么?
- c# - 如何使用硒下载图像?
- c# - 如何在 c# 中使用 openxml 生成的 word 文档中减小文本的字体大小或间距
- c++ - llvm 深度优先搜索从返回块