2017-03-15 110 views
1

我向一個API提交CURL Post請求,一旦成功返回標題LOCATION部分資源URL的狀態「201 Created」。我想要的是自動檢索新創建的資源,但到目前爲止還沒有這樣做。我試過設置curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);但無濟於事。值得注意的是該資源確實需要GET請求。PHP Curl - 跟隨「201 Created」響應標題的位置

我不知道,如果它的狀態代碼是一個201,或者如果請求方法需要改變從POSTGET,但由於某種原因它不遵循LOCATION頭。提取curl_getinfo($ch,CURLINFO_EFFECTIVE_URL);似乎證實了這一點,因爲結果與原始URL相同,而不是新的LOCATION

作爲最後的手段,我已經考慮簡單地解析頭文件並創建一個新的CURL請求,但這不會是最佳的,而且我猜測我只是缺少一些簡單的東西來使這項工作按需要。

如何獲得CURL自動跟蹤並向LOCATION提交GET請求,並返回201響應?

回答

3

你不能。

With curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl請按照響應LOCATION僅限於3xx狀態碼。

AFAIK並聲明作爲文件沒有辦法迫使捲曲跟隨201位迴應的位置。

您必須解析標頭,獲取LOCATION,然後發出第二個捲曲請求。

以下位置的狀態不同於3xx將是一個異常。此外,從curl命令行工具和C庫documentation-L, --location -- (HTTP) If the server reports that the requested page has moved to a different location (indicated with a Location: header and a 3XX response code), this option will make curl redo the request on the new place


給人一種快看捲曲源代碼,你會發現在/lib/http.c功能Curl_http_readwrite_headers

位置遵循的是裏面有這個條件處理:

else if((k->httpcode >= 300 && k->httpcode < 400) && 
     checkprefix("Location:", k->p) && 
     !data->req.location) { 
    /* this is the URL that the server advises us to use instead */ 
    char *location = Curl_copy_header_value(k->p); 
    if(!location) 
    return CURLE_OUT_OF_MEMORY; 
    if(!*location) 
    /* ignore empty data */ 
    free(location); 
    else { 
    data->req.location = location; 

    if(data->set.http_follow_location) { 
     DEBUGASSERT(!data->req.newurl); 
     data->req.newurl = strdup(data->req.location); /* clone */ 
     if(!data->req.newurl) 
     return CURLE_OUT_OF_MEMORY; 

     /* some cases of POST and PUT etc needs to rewind the data 
     stream at this point */ 
     result = http_perhapsrewind(conn); 
     if(result) 
     return result; 
    } 
    } 
} 

位置之後與300399

+0

謝謝,我開始懷疑這一點。你能添加一個鏈接到描述這個的文檔嗎?我認爲這會改善答案,我很樂意接受它。 – billynoah

+0

http://php.net/manual/en/function.curl-setopt.php – Paolo

+1

我刪除了評論,還發布了一部分源代碼,它提供了對文檔的解釋是正確的線索(狀態沒有重定向超出範圍3xx) – Paolo

0

我明白這並沒有回答你的問題在純粹意義之間的狀態碼它 - 我的解決方案甚至沒有在PHP中,但這裏有一種方法(使用jq)遵循201 cURL:

shrinkImageFunction() { 
echo 
echo Compressing $1 . . . 

curl --user api: https://tinypng.com/developers \ 
     --data-binary @$1 \ 
     -o .$1-json \ 
     -s \ 
     https://api.tinify.com/shrink 

cat .$1-json | jq -r '.output.url' > .$1-url 

url=$(cat .$1-url) 

if [ -z "$url" ]; then 
     echo Something went wrong 
     return 
fi 

echo Downloading $url . . . 

echo 
curl -o compressed-$1 $url 
echo 

rm .$1-json 
rm .$1-url 
} 

# alias for using tinypng 
alias shrinkImage=shrinkImageFunction 

我今天在做類似的研究的時候把它扔在了一起,並且認爲我會分享遇到這個問題的同時尋找選擇。

它可以很容易地被調整來解析http 201標題響應使用sed或類似的而不是jq我在解析http提供的身體json響應tinypng(僅供參考 - 我不隸屬於他們)。