【发布时间】:2014-12-12 13:59:20
【问题描述】:
我正在尝试使用 php curl 连接到我构建的 api。我无法使用 curl 很好地创建自定义标头,试图指示一些标头信息,例如 Content-Type、Content-Length。
我也在努力理解如何正确发送(发布)一个充满 json 数据的 http-body。
基本上我要做的是让标题具有 Content-Type、Content-Length、一些自定义字段,如 $api => "45234523452345"、$hashedKey => "32413211234123"。
在 http-body 中发送一个有效载荷(一个 json 编码的数组或 json 编码的多维数组)。
这是我现在尝试使用的。
public function mainRequest($url, $apiKey) {
$payload = array(
'test' => 'data'
);
$jsonPayload = urlencode(json_encode($payload));
$encyptedKey = $this->dataEncyptor->hashData($apiKey);
$header = array(
'Content-Type:' => 'application/json',
'Content-Length:' => strlen($jsonPayload),
'x-public' => $apiKey,
'x-hash' => $encyptedKey
);
$fp = fopen(dirname(__FILE__).'/errorlog.txt', 'w');
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_STDERR, $fp);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonPayload);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// curl_setopt($ch, CURLOPT_POST, 1);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
在我的错误日志中,我得到了这个:
* About to connect() to local.nslim.ca port 80 (#0)
* Trying 127.0.0.1...
* connected
* Connected to local.nslim.ca (127.0.0.1) port 80 (#0)
> POST /datacheck HTTP/1.1
Host: local.nslim.ca
Accept: */*
Content-Length: 29
Content-Type: application/x-www-form-urlencoded
* upload completely sent off: 29 out of 29 bytes
< HTTP/1.1 404 Not Found
< Date: Fri, 17 Oct 2014 03:05:43 GMT
< Server: Apache/2.2.25 (Unix) mod_ssl/2.2.25 OpenSSL/0.9.8za DAV/2 PHP/5.5.3
< X-Powered-By: PHP/5.5.3
< Content-Length: 514
< Content-Type: text/html
<
* Connection #0 to host local.nslim.ca left intact
* Closing connection #0
而输出到屏幕的是:
HTTP/1.1 404 Not Found 日期:2014 年 10 月 17 日星期五 03:06:07 GMT 服务器:Apache/2.2.25 (Unix) mod_ssl/2.2.25 OpenSSL/0.9.8za DAV/2 PHP/5.5.3 X-Powered-By:PHP/5.5.3 内容长度:514 内容类型:text/html 404 页面未找到
找不到您要查找的页面。检查地址栏以确保您的 URL 拼写正确。如果一切都失败了,您可以通过下面的链接访问我们的主页。 访问主页
cURL setopt 是否需要按任何特定顺序排列?
感谢您的帮助!
【问题讨论】: