簡體   English   中英

PHP CURL 不自動添加Content-Length header

[英]PHP CURL does not automatically add Content-Length header

我已經被這個問題困擾了一段時間。 我有一個簡單的代理代碼,可以將查詢從這個 PHP 腳本重定向到另一個應用程序。

事情是 GET 的工作就像一個魅力,但 POST 卻沒有。 我發現當我從 php-curl 進行 POST 查詢時,它沒有附加 Content-Length header。因此,實際的應用程序無法從請求中檢索數據,並且顯然無法響應。 所以我決定手動設置它,但現在實際的應用程序沒有收到完整的主體,但出於某種原因只收到其中的一部分,即使內容長度是正確的。

所以我有兩個問題:

  1. 為什么curl不自動設置header? 從我在文檔中閱讀的內容來看,它應該是。
  2. 如何正確計算內容長度? 因為在測試期間,我什至試圖根據 Content-Length header 對它進行硬編碼,我在查詢實際應用程序時從 postman 獲得。

代碼有點簡單:

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 = 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 header 存在。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM