首页 > 解决方案 > PHP curl 带有引号和空格的长链接

问题描述

需要使用 cURL 从 php 访问 REST api。这个 ia 休息链接:

http://username:password@172.16.59.225:8042/tools/find -d '{"Level":"Study","Expand":false,"Query":{"StudyDate":"20191226-20200324"}}'

正如你看到的很多 " 和空白。

我试图像这样手动准备字符串:

$url = "http://172.16.59.225/tools/find -d '{\"Level\":\"Study\",\"Expand\":false,\"Query\":{\"StudyDate\":\"20191226-20200324\"}}'";

and pass password using: curl_setopt($ch, CURLOPT_USERPWD, "username:password");

我用过urlencode()curl_escape没有任何效果。同时,此链接在 Linux cmd 中与 curl 一起使用可以完美运行。

可行吗?

标签: phpcurl

解决方案


试试这个,--data或者-d参数是sends the specified data in a POST request to the HTTP server Source

$url = 'http://172.16.59.225/tools/find';
$postdata = '{"Level":"Study","Expand":false,"Query":{"StudyDate":"20191226-20200324"}}';

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERPWD, "username:password");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$result = curl_exec($ch);
curl_close($ch);
print_r ($result);

推荐阅读