簡體   English   中英

請求休息API不適用於php curl,但適用於PhpStorm Rest Client

[英]Request to rest api doesn't work by php curl but works by PhpStorm Rest Client

我正在嘗試通過curl發送請求以休息api,但我始終會收到404響應。 當我通過PhpStorm執行相同的請求時,我的請求可以正常工作。 我在其余客戶端中設置與curl中相同的標頭。 我做錯了什么? 以下是我的php代碼和其余客戶端配置的屏幕截圖

    $postfields = array(
        'SUBSCRIPTION'                  => 'testlist',
        "HTTP_REDIRECT"                 => 'https://testsite.com',
        "HTTP_REDIRECT_ERROR"           => 'https://testsite.com/error',
        "email"                         => 'test+100@gmail.com',
        "Sprache"                       => 'DE'
    );


    $uri = $uri . '?=' . http_build_query($postfields); // value of uri is http://web.mailingsystem.com/subscription/servlet?=SUBSCRIPTION=testlist&HTTP_REDIRECT=https%3A%2F%2Ftestsite.com%2F&HTTP_REDIRECT_ERROR=https%3A%2F%2Ftestsite.com%2Ferror&email=test%2B100A%40gmail.com&Sprache=DE
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $uri);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_VERBOSE, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 60);
    curl_setopt($ch, CURLOPT_ENCODING, "");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_MAXREDIRS, 1);
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;from testshop;os:".PHP_OS.";)");
    curl_setopt($ch, CURLINFO_HEADER_OUT, true);

    $headers = [
        'Content-Length:'
    ];
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);


    $content = curl_exec($ch);
    $error = curl_error($ch);
    $response = curl_getinfo($ch);
    curl_close($ch);

其余客戶端配置

首先,您發送不完整的“ content-length”標頭。 目標服務器很可能會將其視為“ content-length:0”,但是您應該聯系api的開發人員並告訴他們進行修復,因此它返回400 Bad Request響應,而不是404 Not Found響應,然后您應該修復您的代碼,使其具有正確的content-length標頭。 最好的方法是根本不插入content-length標頭,這會使curl為您生成正確的標頭(當您有請求正文時)

其次,您的RestClient似乎正在使用multipart/form-data編碼,但是您的curl代碼根本沒有請求正文,數據在GET網址中,請解決此問題,以便curl與CURLOPT_POSTFIELDS與RestClient匹配,像curl_setopt($ch,CURLOPT_POSTFIELDS,http_build_query($postfields)); ,然后從網址中刪除數據。 可能是因為您的網址格式不正確(包含發布數據主體),所以您收到404錯誤

暫無
暫無

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

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