如何在PHP CURL中从POST切换到GET

时间:2009-08-04 01:50:11

标签: php post curl get

我尝试从之前的Post请求切换到Get请求。假设它是一个Get但最终会发布一个帖子。

我在PHP中尝试了以下内容:

curl_setopt($curl_handle, CURLOPT_POSTFIELDS, null);
curl_setopt($curl_handle, CURLOPT_POST, FALSE);
curl_setopt($curl_handle, CURLOPT_HTTPGET, TRUE);

我错过了什么?

其他信息: 我已经有一个设置为POST请求的连接。这成功完成但稍后当我尝试重用连接并使用上面的setopts切换回GET时,它仍然在内部使用不完整的POST头进行POST。问题是它认为它正在进行GET但最终放置一个没有content-length参数的POST头,并且连接失败并出现411 ERROR。

4 个答案:

答案 0 :(得分:103)

确保在执行GET请求时将查询字符串放在URL的末尾。

$qry_str = "?x=10&y=20";
$ch = curl_init();

// Set query data here with the URL
curl_setopt($ch, CURLOPT_URL, 'http://example.com/test.php' . $qry_str); 

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 3);
$content = trim(curl_exec($ch));
curl_close($ch);
print $content;
With a POST you pass the data via the CURLOPT_POSTFIELDS option instead 
of passing it in the CURLOPT__URL.
-------------------------------------------------------------------------

$qry_str = "x=10&y=20";
curl_setopt($ch, CURLOPT_URL, 'http://example.com/test.php');  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 3);

// Set request method to POST
curl_setopt($ch, CURLOPT_POST, 1);

// Set query data here with CURLOPT_POSTFIELDS
curl_setopt($ch, CURLOPT_POSTFIELDS, $qry_str);

$content = trim(curl_exec($ch));
curl_close($ch);
print $content;

CURLOPT_HTTPGET注意TRUE(强调添加):

  

[将CURLOPT_HTTPGET等于] {{1}}设置为重置 HTTP请求方法为GET。
  由于GET是默认值,因此仅在请求方法已更改时才需要这样做。

答案 1 :(得分:50)

在调用curl_exec($ curl_handle)

之前添加此项
curl_setopt($curl_handle, CURLOPT_CUSTOMREQUEST, 'GET');

答案 2 :(得分:33)

解决:问题在于:

我通过POST_CUSTOMREQUEST设置了_POST_CUSTOMREQUEST保持为POST_POST切换为_HTTPGET 。服务器认为_CUSTOMREQUEST的标题是正确的标题,然后返回411。

curl_setopt($curl_handle, CURLOPT_CUSTOMREQUEST, 'POST');

答案 3 :(得分:2)

默认情况下,CURL请求是GET,您不必设置任何选项来发出GET CURL请求。