PHP CURL不会自动添加Content-Length标头

问题描述 投票:0回答:1

我已经被这个问题困扰了一段时间了。我有一个简单的代理代码,可将查询从此PHP脚本重定向到另一个应用程序。

事情是GET的工作很吸引人,而POST却没有。我已经发现,当我从php-curl进行POST查询时,它没有附加Content-Length标头。因此,实际的应用程序无法从请求中检索数据,并且显然无法响应。因此,我决定手动设置它,但是现在实际的应用程序由于内容的原因,即使内容长度正确,也无法接收到完整的正文,而仅收到一部分。

所以我有2个问题:

  1. 为什么不卷曲自动设置标题?因为从我在文档中阅读的内容应该是。
  2. 如何正确计算内容长度?因为在测试过程中,我甚至尝试根据Content-Length标头对它进行硬编码,当我向实际应用查询时,该标头是从邮递员那里获得的。

代码有点简单:

function forward(FromRequest $request)
{
    $curl = curl_init();

    curl_setopt($curl, CURLOPT_URL, IT_HOST . $request->getUrl());
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $request->getMethod());
    curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);

    curl_setopt($curl, CURLOPT_HTTPHEADER, array(
        "cache-control: no-cache",
        "content-type: application/json",
        $request->getAuthHeader(),
        ));

    if ($request->getMethod() === 'POST') {
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $request->getData());
    }


    $response = curl_exec($curl);
    $err = curl_error($curl);

    curl_close($curl);

    if ($err) {
        var_dump($err);
        throw new FromRequestException('Cant make a request');
    }

    return $response;
}

此外,$request->getData()正确地从当前请求中提取数据:$request->data = file_get_contents("php://input");

php curl php-curl
1个回答
0
投票

执行此特定代码时,我无法重现该问题:

<?php
    $curl = curl_init();

    curl_setopt($curl, CURLOPT_URL, "http://127.0.0.1:9999");
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);

    curl_setopt($curl, CURLOPT_HTTPHEADER, array(
        "cache-control: no-cache",
        "content-type: application/json",
        "auth-header: foo",
        ));

        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, '{"days_up_to":12,"territory":[]}');


    $response = curl_exec($curl);
    $err = curl_error($curl);

PHP / libcurl发送此特定请求:

POST / HTTP/1.1
Host: 127.0.0.1:9999
Accept: */*
cache-control: no-cache
content-type: application/json
auth-header: foo
Content-Length: 32

{"days_up_to":12,"territory":[]}

并且,如果您查看请求的第7行,则显示Content-Length标头。

© www.soinside.com 2019 - 2024. All rights reserved.