使用PHP卷曲我想连接到我已经建立的api。我无法用curl创建自定义标题,试图指定某些标题信息,例如Content-Type,Content-Length。如何创建自定义标题并使用php curl发送json数据?
我也在努力理解如何正确发送(发布)一个完整的json数据的http-body。
本质上,我试图做的是拥有Content-Type,Content-Length,一些自定义字段,如$ api =>“45234523452345”,$ hashedKey =>“32413211234123”。
那么在http-body中发送一个有效负载(数组json编码或json编码的多维arry)。
这是我现在想要使用的。
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未找到日期:星期五,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 Page Not Found
页面你正在寻找无法找到。检查地址栏以确保您的URL拼写正确。如果一切都失败了,您可以通过下面的链接访问我们的主页。 访问首页
cURL setopt是否需要按照任何特定顺序?
感谢您的帮助!
啊我的网址是正确的,因为我已经得到了到它发送一个101继续点。当我通过浏览器访问网址时,它可以正常工作。我正在尝试将内容类型设置为application/json。 – floor 2014-10-17 04:54:47
可能有助于在接收端发布代码。如果脚本实际上在那里,那么你必须明确告诉它在你的代码中发送一个404的地方。 – miken32 2014-10-17 04:57:50
对不起,跳过您设置MIME类型的位置。在Content-Type之后丢失冒号;你可以从日志中看到,mime类型被设置为application/x-www-form-urlencoded。 – miken32 2014-10-17 05:01:49