2015-11-06 111 views
0

所以我試圖發送一個HTTPS POST請求到一個網站,但捲曲不設置我的發佈數據,也沒有我的標題。 這裏是我的代碼(我改變了域名和值):PHP捲曲不解析POST數據

<?php 

//Create connection 
$ch = curl_init(); 

//Set the headers 
$headers = array(); 
$headers[] = "Connection: Keep-Alive"; 
$headers[] = "Host: website.com"; 
$headers[] = "Content-Type: application/x-www-form-urlencoded"; 
$headers[] = "Something: Something_Data"; 

//Set the POST data 
$headers = array(); 
$headers[] = "Connection: Keep-Alive"; 
$headers[] = "Host: website.com"; 
$headers[] = "Content-Type: application/x-www-form-urlencoded"; 
$headers[] = "Something: Something_Data"; 

// Configure the request (HTTPS) 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
curl_setopt($ch, CURLOPT_URL, "https://website.com/test"); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_USERAGENT, "MyUserAgentHere"); 
curl_setopt($ch, CURLOPT_HEADER, true); 
curl_setopt($ch, CURLOPT_POST, 1); //just to be sure... 

//Set the POST data and Headers 
curl_setopt($ch, CURLOPT_POSTFIELDS, urlencode("DATA1=VAL1&DATA2=VAL2")); 
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); 

$result=curl_exec($ch); 
echo $result; 

curl_close($ch); 
?> 

所以基本上我試圖發送一個HTTPS POST請求https://website.com/test」的請求被髮送,我也得到一個答案,但因爲某些原因它不解析POST數據也不是頭

這是我在提琴手的請求:

POST https://website.com/test HTTP/1.1 
Host: website.com 

這裏是請求的答案:

HTTP/1.1 400 Bad Request 
Date: Fri, 06 Nov 2015 00:57:15 GMT 
Server: Apache 
Cache-Control: no-store 
Pragma: no-cache 
Connection: close 
Content-Type: application/json;charset=UTF-8 
Content-Length: 158 

{"error":"unsupported DATA1"} 

正如您所見,由於某種原因,POST數據和標題未在我的請求中設置。我不知道爲什麼curl不設置我的標題和我的帖子字段。

信息:我正在使用XAMPP和php5。

+1

嘗試從你的CURL請求中取出DATA1,看看你是否得到相同的響應。 – smcjones

+0

您是否可以控制要發佈的服務器?如果是這樣,你可以發出一個'print_r($ _ POST);'? – Mike

+1

你爲什麼要設置'$ headers'兩次? – Machavity

回答

2

您不應對整個參數字符串進行網址編碼,這將對=&進行編碼,以使它們不再是分隔符。你應該只對這些值進行編碼。

curl_setopt($ch, CURLOPT_POSTFIELDS, 'DATA1=' . urlencode($val1) . '&DATA2' . urlencode($val2)); 

您可以使用數組來替代,而cURL會爲您執行編碼。

curl_setopt($ch, CURLOPT_POSTFIELDS, array('DATA1' => $val1, 'DATA2' => $val2)); 

如果使用陣列機構,取出Content-type: application/x-www-form-urlencoded頭,因爲捲曲發送它在multipart/form-data格式。

+0

我只是改變了它,可悲的是我的請求仍然是空的。我不知道爲什麼我的請求是空的。 注:我編輯我的代碼更新。 – StackKev

+1

請回答這個問題。任何人如果不能在你的問題中看到原始代碼,誰能理解我的答案的原因? – Barmar

+0

嘗試取出'Content-type'標頭,這不是cURL編碼數組的方式。 – Barmar