【问题标题】:Trouble with php cURL library and REST POST requestphp cURL 库和 REST POST 请求出现问题
【发布时间】:2013-02-21 19:40:07
【问题描述】:

在我发布的 API 发布了他们的 API 的最终版本后,我遇到了 REST POST 请求的问题。它工作正常,并且有人告诉我,在新版本中,服务器对“应用程序/json”的类型更加严格。以下 cli curl 命令运行流畅:

cat json.txt|curl -v -k -u user:password -F 'exchangeInstance=@-;type=application/json'  https://my.url.here

但是,我需要在代码中执行此操作。使用 php curl 库,我得到了一个简单的测试脚本,如下所示:

  $post = array(
    "exchangeInstance" => $json_string,
    "type" => "application/json",
  );
  $url = 'myurlhere';

  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
  curl_setopt($ch, CURLOPT_USERPWD, "user:pass");
  curl_setopt($ch, CURLOPT_POST, true);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

  $result = curl_exec($ch);
  $info = curl_getinfo($ch);

  var_dump($post);
  var_dump($result);
  echo $result;
  var_dump($info);

当我阅读文档时,如果我将数组作为 CURLOPT_POSTFIELDS 传递,标题中的 Content-type 应自动设置为“multipart/form”,然后我将元素传递的类型设置为“application/” json'在数组中。

但是,该 api 没有收到我的 POST 请求。我从他们那里得到一个错误,清楚地表明他们正在接收一个 GET 请求。这怎么可能?我错过了什么?

【问题讨论】:

  • 你有 followlocation=true。如果服务器正在执行重定向,则将通过 GET 获取重定向到的 url,即使您从 POST 开始。把它关掉,看看你会得到什么。
  • 哇。这当然符合我正在处理的内容,但我找不到任何文档。有什么线索吗?我有一种感觉,我在 A 点进行身份验证,并重定向到 B 点。我被重定向到特定端口,但我使用的 url 与 CLI 命令中的相同。

标签: php rest post curl


【解决方案1】:

卷曲-F !== -d

$post = array(
    "exchangeInstance" => sprintf('@%s;type=application/json', $json_string),   
);

【讨论】:

  • 这很有趣。感谢上帝赐予聪明人。我确定这是问题的一部分,但目前还不是全部。当我知道更多时,我会回复 - 谢谢!
  • 因此,除非我将路径传递给文件,否则这实际上不起作用。否则它会发送一个附加了@符号的字符串......我没有找到一种方法来设置单个mime多部分标题的内容类型而不传递文件。在我看来,应该有比将字符串写入临时文件,然后将其发送到 curl 库更好的方法......有什么想法吗?
猜你喜欢
  • 1970-01-01
  • 2019-03-31
  • 1970-01-01
  • 2016-01-03
  • 1970-01-01
  • 2020-09-07
  • 1970-01-01
  • 1970-01-01
  • 2017-06-08
相关资源
最近更新 更多