【问题标题】:Convert terminal cURL command to PHP cURL request将终端 cURL 命令转换为 PHP cURL 请求
【发布时间】:2014-04-12 20:48:37
【问题描述】:

我正在尝试从 PHP 向 Here Maps 的 RESTFUL Batch API 发送 cURL 请求。

文档指出,使用此 cURL 脚本,我可以将包含所需数据的数据文件发送给他们:

curl -X POST -H "Content-Type: text/plain" --data-binary @addresses.txt
            "http://batch.geocoder.cit.api.here.com/6.2/jobs?
         &app_code=AJKnXv84fjrb0KIHawS0Tg
         &app_id=DemoAppId01082013GAL
         &action=run
         &header=true
         &inDelim=;
         &outDelim=,
         &outCols=recId,latitude,longitude,locationLabel
         &mailto=<my_email>
         &outputcombined=true
         &language=de-DE"

我正在尝试将其转换为 PHP。我想出了以下代码:

$cURLHandler = curl_init();
$url = "http://batch.geocoder.cit.api.here.com/6.2/jobs?&app_code=AJKnXv84fjrb0KIHawS0Tg&app_id=DemoAppId01082013GAL&action=run&mailto=trisztanthar@mailinator.com&outCols=recId,latitude,longitude,locationLabel&outputcombined=true&inDelim=;&outDelim=;";
if($cURLHandler) {
    curl_setopt($cURLHandler, CURLOPT_HTTPHEADER, array('Content-Type: text/plain')); 
    curl_setopt($cURLHandler, CURLOPT_BINARYTRANSFER, 1);
    curl_setopt($cURLHandler, CURLOPT_POST, 1);
    curl_setopt($cURLHandler, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($cURLHandler, CURLOPT_POSTFIELDS, array('addresses' => new CurlFile("./batchjob.txt", 'text/plain', "batchjob.txt")));
    curl_setopt($cURLHandler, CURLOPT_URL, $url);
    curl_exec($cURLHandler);
    curl_close($cURLHandler);
}
else {
    throw new RuntimeException("Nem sikerült felvenni a kapcsolatot egy távoli szerverrel.");
}

使用时出现如下错误:

仅管道 (|)、分号 (;)、冒号 (:)、制表符 (' ') 和逗号 (,) 允许使用分隔符。

首先我认为该文件有问题,但是我尝试在 unix 终端中使用我尝试与 PHP 一起使用的相同文件运行终端命令,并且它没有任何问题地通过,响应为正确的响应,所以我使用的 PHP 代码 100% 没有发布文件。

我目前正在使用 MAMP 服务器 (OSX) 在 localhost 上进行开发。 batchFile.txt 文件位于 /Applications/Mamp/htdocs/php/ 文件夹 (localhost/php/batchfile.txt) 中。

我做错了什么?

【问题讨论】:

  • 不要暴露你的私有应用密钥。
  • 这是演示应用程序密钥。 :)

标签: php rest curl here-api


【解决方案1】:

在命令行中,您直接将文件作为二进制数据发布。所以发送如下内容。

curl_setopt($cURLHandler, CURLOPT_POSTFIELDS, file_get_contents("batchjob.txt"));

【讨论】:

    猜你喜欢
    • 2016-03-20
    • 2017-05-25
    • 2017-08-03
    • 2016-03-07
    • 2019-06-04
    • 1970-01-01
    • 1970-01-01
    • 2014-08-28
    • 2016-05-20
    相关资源
    最近更新 更多