【问题标题】:Content Type not being set in cURL in PHP内容类型未在 PHP 中的 cURL 中设置
【发布时间】:2014-12-31 06:16:49
【问题描述】:

我正在尝试使用 cURL 向 API(具体来说是 Xero)发送请求,但我显然发送的是空请求。我检查了 cURL 信息,看起来我没有设置 Content-Type,即使我已经在代码中设置了它。

这是我的代码:

    $content = $this->getContent();
    $headers = [
        "Content-Type: application/x-www-form-urlencoded",
        "Content-Length: " . strlen($content),
        "Connection: close"
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $this->getUrl());
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_HEADER, true);

    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $content);

    de($headers, curl_getinfo($ch));

de() 是一个“转储和退出”函数,它输出如下:

 array(3) {
  [0] =>
      string(47) "Content-Type: application/x-www-form-urlencoded"
  [1] =>
      string(20) "Content-Length: 1003"
  [2] =>
      string(17) "Connection: close"
}

array(26) {
  'url' =>
  string(41) "https://api.xero.com/api.xro/2.0/Invoices"
  'content_type' =>
  NULL
  'http_code' =>
  int(0)
  'header_size' =>
  int(0)
  'request_size' =>
  int(0)
  'filetime' =>
  int(0)
  'ssl_verify_result' =>
  int(0)
  'redirect_count' =>
  int(0)
  'total_time' =>
  double(0)
  'namelookup_time' =>
  double(0)
  'connect_time' =>
  double(0)
  'pretransfer_time' =>
  double(0)
  'size_upload' =>
  double(0)
  'size_download' =>
  double(0)
  'speed_download' =>
  double(0)
  'speed_upload' =>
  double(0)
  'download_content_length' =>
  double(-1)
  'upload_content_length' =>
  double(-1)
  'starttransfer_time' =>
  double(0)
  'redirect_time' =>
  double(0)
  'certinfo' =>
  array(0) {
    }
  'primary_ip' =>
  string(0) ""
  'primary_port' =>
  int(0)
  'local_ip' =>
  string(0) ""
  'local_port' =>
  int(0)
  'redirect_url' =>
  string(0) ""
}

据我所见,我正确设置了标题(常量拼写正确,我没有多次设置它们)。我做错了什么?

【问题讨论】:

  • 你应该在调用 curl_getinfo 之前转移一些东西
  • 啊,是的,我的错。看起来问题是别的:(

标签: php http curl header content-type


【解决方案1】:

首先检查curl_error函数click me for detail!!

因为您的网址是https。所以遵循ssl验证过程。

非正式修正:

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

正式修复:

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_CAINFO, getcwd() . "/CAcerts/your_certificate.crt");

证书在哪里?

  1. 在火狐浏览器中浏览网址

  1. 点击地址栏左侧的锁板

  2. 然后点击更多信息

  3. 现在点击view certificate按钮

  4. 在打开的弹出窗口中,您将在该点击详细信息选项卡中看到两个选项卡(快捷方式 ALT + D)。

  5. 然后点击导出按钮,保存证书

  1. 这是你必须在这里给出的路径

    curl_setopt($ch, CURLOPT_CAINFO, getcwd() . "/CAcerts/your_certificate.crt")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多