2017-03-10 59 views
1

我瘋了,試圖弄清楚一個簡單的代碼片段發生了什麼。PHP> cURL>覆蓋http方法>順序請求

我會寫更少的代碼,因爲我可以專注於這個問題。

目標

執行與相同的句柄,但不同的選擇兩個或更多的捲曲請求。

捲曲包裝部

public function __construct(){ 
    $this->handle = curl_init(); 
} 

public function execute(){ 
    $handle = $this->handle; 
    # ... some default, not relevant, options ... # 
    # Retrieve the http method 
    $http_method = $this->http_method; 
    # Set the method 
    switch($http_method){ 
     case 'GET': 
      curl_setopt($handle, CURLOPT_HTTPGET, true); 
      break; 
     case 'POST': 
      curl_setopt($handle, CURLOPT_POST, true); 
      break; 
     default: 
      curl_setopt($handle, CURLOPT_CUSTOMREQUEST, $http_method); 
      break; 
    } 
    # Set the url 
    curl_setopt($handle, CURLOPT_URL, $this->url); 
    # Retrieve the payload 
    $payload = $this->payload; 
    # Set the payload 
    if(!empty($payload)){ 
     # Specify data to send 
     curl_setopt($handle, CURLOPT_POSTFIELDS, $payload); 
    } 
    # Execute the request 
    $result = curl_exec($handle); 
    # Reset the handle 
    curl_reset($handle); 
    # Update the handle 
    $this->handle = $handle; 
} 

使用

# First 
    $obj->setHttpMethod('post'); 
    $obj->setURL("someurl"); 
    $payload = array(
     'field' => 'value' 
    ); 
    $obj->setPayload($payload); 
    $result = $obj->execute(); 

    # Second 
    $obj->setHttpMethod('get'); 
    $obj->setURL("anotherurl"); 
    $result = $obj->execute(); 

結果的樣品

其次被作爲一個POST,而不是GET執行。

結論提前

感謝:我會愛任何建議。

+0

嗨布魯諾,哪個PHP版本和SO? –

+0

沒有測試,猜測...你應該設置你的有效載荷爲'null' ... – Ikari

+0

@Saitama,因爲我想像它像我一樣愚蠢。非常感謝:它解決了!唯一的問題是爲什麼curl_reset()不能重置CURLOPT_POSTFIELDS? –

回答

0

只是將它張貼作爲回答:

當你做一個POST請求的後場已經被保留,然後做一個GET請求。

因此,將字段更改爲null,將使cUrl執行GET請求而不是。