我有一个PHP curl语句,由于某种原因,该语句发送的格式不正确。无论如何,使用POST方法发送的正文都是空的。它只是发送标题。我似乎不知道为什么。
我正在对正在调用此功能的函数中的$data
有效载荷进行JSON编码。
(php5.6 / Apache)
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLINFO_HEADER_OUT, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'X-xx-MerchantId: ' . $this->opt['merchantId'],
'X-xx-REST-API-Key: ' . $this->opt['apiKey'],
'Content-Type: application/json',
'Accept: application/json'
));
if ($method == "POST") {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
}
elseif ($method == "GET") {
curl_setopt($ch, CURLOPT_POST, 0);
curl_setopt($ch, CURLOPT_HTTPGET, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
}
elseif ($method == "PUT") {
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
}
elseif ($method == "DELETE") {
curl_setopt($ch, CURLOPT_PUT, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
}
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_USERAGENT, "PHPxx v2");
$result_text = curl_exec($ch);
$curl_request_info = curl_getinfo($ch);
curl_close($ch);
使用一个用于API调用的测试工具,我已经验证了发送的curl是否显示空白。
在对真实端点进行测试时,endpoing返回一个错误,似乎暗示没有主体。 (411状态码)
curl_getinfo($ ch)的转储:
答案 0 :(得分:2)
这看起来像您API KEY之后有两行。两个换行符指示“标题结束,开始内容”。因此,您将可怜的事情弄糊涂了。
您的第一次调试显示“ Content-Type”和“ Accept”标头未正确通过。
第二次调试显示未使用相同的两个标头;显示两个换行符,还显示您正在传递一些内容。
删除这些换行符,您应该是对的。