【问题标题】:Passing a URL into a JSON array将 URL 传递到 JSON 数组
【发布时间】:2016-05-13 05:27:57
【问题描述】:

我正在尝试在 PHP 中执行一个使用 JSON 数组的 curl 语句。我将在下面发布我的代码,并稍微解释一下我想要做什么

function doPost($url, $user, $password, $params) {
  $authentication = 'Authorization: Basic '.base64_encode("$user:$password");
  $http = curl_init($url);
  curl_setopt($http, CURLOPT_SSL_VERIFYHOST, false);
  curl_setopt($http, CURLOPT_SSL_VERIFYPEER, false);
  curl_setopt($http, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($http, CURLOPT_URL, $url);
  curl_setopt($http, CURLOPT_POST, true);
  curl_setopt($http, CURLOPT_POSTFIELDS, $params);
  curl_setopt($http, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json', $authentication));
  return curl_exec($http);
}

$link = "http://link.it/i.htm?id=55&key=23987gf2389fg";
$phone = '5551231234';
$phone = '1' . $phone;

//Write message
$msg = "Click here " . $link;
$params = '[{"phoneNumber":"'.$phone.'","message":"'.$msg.'"}]';

//Send message
$return = doPost('https://api.link.com','username','password',$params);
echo $return;

参数最终是

$params = '[{"phoneNumber":"15551231234","message":"Click here http://link.it/i.htm?id=55&key=23987gf2389fg"}]';

一切看起来都不错。如果 $msg 变量中没有链接,则由 params 创建的 JSON 数组实际上可以完美运行。我能够成功执行 CURL 调用。唯一失败的时候是我将链接添加到我的 $msg 变量。

我已经联系了 API 的支持团队,他们告诉我一切都应该正常工作。

此时我猜测链接需要以某种方式转义,然后才能写入 JSON 数组。我试过用反斜杠转义冒号和正斜杠,但它不能解决问题。有没有人可以阐明如何传递网址?

提前谢谢你!!

【问题讨论】:

  • 不要手工制作 JSON。使用 PHP json_encode() 函数。它负责创建正确的 JSON。

标签: javascript php json curl callfire


【解决方案1】:

不要手动构建 JSON。构造和数组或对象,然后在其上调用 json_encode()。

$params = array();
$object = array("phone"=>$phone, "message"=>$linkMsg);
$params[] = (object) $object;

$param_json_string = json_encode($params);

那么当使用curl通过POST提交JSON时,需要在header中指定字符串的长度。

curl_setopt($http, CURLOPT_HTTPHEADER, 
            array( 'Content-Type: application/json', 
                   'Content-Length: '. strlen($param_json_string)));           

当然,这是您设置的身份验证等其他标头的补充(正如我看到您在 doPost() 方法中所做的那样)。

【讨论】:

  • 等到stackoverflow精灵批准对这篇文章的编辑,以便您可以看到代码示例
  • 不幸尝试了,curl调用仍然返回错误。一定是 API 出错。被编码的json是完美的"[{"phoneNumber":"15551231234","message":"Click here http:\/\/link.it\/i.html?id=55&key=247a626c8b28293bf1e5"}]"
  • 一个有效的 JSON 字符串可能仍然无法在 HTTP 请求中使用,通过对其进行 urlencoding 它将转义任何特殊的 HTTP 字符,如空格、&? 等。跨度>
  • 所有帮助都很棒。我尝试了两件事。我对整个 JSON 字符串 $params = json_encode($params); $safeParams = urlencode($params); 进行了 urlencoded,当我执行 curl 调用时,它返回了错误 {"httpStatusCode":422,"internalCode":0,"message":"Unable to convert entity : Unexpected character ('%' (code 37)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')\n at [Source: org.apache.catalina.connector.CoyoteInputStream@a14933; line: 1, column: 2], error type: JsonParseException"}
  • 我还在消息$linkMsg = "Click here " . $link; $linkMsg = urlencode($linkMsg); 中的链接上尝试了urlencode,但响应更加模棱两可,只是说消息中有错误。嗯……
猜你喜欢
  • 2012-06-19
  • 1970-01-01
  • 1970-01-01
  • 2015-03-15
  • 2015-02-19
  • 2018-01-30
  • 1970-01-01
  • 2011-11-13
  • 1970-01-01
相关资源
最近更新 更多