【问题标题】:PHP cURL Content-Type is not set未设置 PHP cURL Content-Type
【发布时间】:2013-11-07 07:38:00
【问题描述】:

我想连接一个简单的网络服务。为了发布一些XML,这将在Web服务端正确进行,我需要准备一个正确的请求。我为此使用cURL:

try {
    $ch = curl_init();

    if (FALSE === $ch)
        throw new Exception('failed to initialize');

    curl_setopt($ch, CURLOPT_URL,"192.168.1.37");
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                                            'Content-Type: application/xml',
                                            'Connection: Keep-Alive'
                                            ));
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
    curl_setopt($ch, CURLOPT_PROXY, '');
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_FRESH_CONNECT, TRUE);
    curl_setopt($ch, CURLOPT_HTTPHEADER,array("Expect:  "));
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS,$xml);


    $request=  curl_getinfo($ch);
    var_dump($request);


    $content = curl_exec($ch);


    if (FALSE === $content)
        throw new Exception(curl_error($ch), curl_errno($ch));



} catch(Exception $e) {

    trigger_error(sprintf(
        'Curl failed with error #%d: %s',
        $e->getCode(), $e->getMessage()),E_USER_ERROR);

}

一切都应该没问题。首先我显示来自curl_getinfo($ch); 的请求正文,然后显示来自$content 变量的响应。

请求发送到服务器的唯一限制是 Content-Type 标头 - 它必须是 application/xml 否则服务器将响应错误(这不是我的想法,我对此无能为力)

这里是输出请求:

array(21) { ["url"]=> string(68) "192.168.1.37" ["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"]=> float(0) ["namelookup_time"]=> float(0) ["connect_time"]=> float(0) ["pretransfer_time"]=> float(0) ["size_upload"]=> float(0) ["size_download"]=> float(0) ["speed_download"]=> float(0) ["speed_upload"]=> float(0) ["download_content_length"]=> float(-1) ["upload_content_length"]=> float(-1) ["starttransfer_time"]=> float(0) ["redirect_time"]=> float(0) ["certinfo"]=> array(0) { } }

回复是HTTP 400 Bad Request

我可以看到 ["content_type"]=> NULL 但我在我的 PHP 代码中设置了这个变量...

谁能告诉我我错过了什么?

【问题讨论】:

标签: php web-services curl


【解决方案1】:

您设置了两次 HTTP_HEADER:

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                                            'Content-Type: application/xml',
                                            'Connection: Keep-Alive'
                                            ));

curl_setopt($ch, CURLOPT_HTTPHEADER,array("Expect:  "));

我想这就是问题所在。第二次设置时,删除第一个设置。

【讨论】:

  • 当然是它!不敢相信这是这么愚蠢的错误。谢谢你的军团!
  • 呃,复制粘贴代码有问题。我有完全相同的行导致完全相同的问题。赞成
猜你喜欢
  • 2020-09-30
  • 2021-12-22
  • 2013-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-02
  • 2014-03-06
  • 2011-05-24
相关资源
最近更新 更多