2017-04-19 85 views
1

我有這樣的方法,其中我試圖用json體發送POST要求:捲曲後無法正常工作(不被髮送體)

public function executePost($url, $theBody, $headers){ 

    $data_string = '{"apple": "fruit", "turnip": "vegetable"}'; // hard coded for now                    
    \Log::info($data_string);                        
    $ch = curl_init($url);                  
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                  
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);                 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                  
    curl_setopt($ch, CURLOPT_HTTPHEADER, array_merge($headers, array(                   
     'Content-Type: application/json',                     
     'Content-Length: ' . strlen($data_string))                  
    ));                             

    $result = curl_exec($ch); 

    \Log::info($result); 
} 

在接收端我沒有得到的數據我做:

\Log::info(\Input::all()); 

我什麼也沒有,即一個空的數組。我似乎無法弄清楚這有什麼問題。

它在使用WAMP的另一臺計算機上工作,我使用的是Ubuntu 16.04和PHP 5.6。

+0

請向我們展示接收端代碼? –

+0

嘗試使用$ _POST = json_decode(file_get_contents(「php:// input」),true)在接收端獲取數據;和print_r($ _ POST);它和var_dump($結果); –

+0

試過了,不起作用。 –

回答

0

儘量讓數據看起來像這樣:

$post = [ 
    'username' => 'user1', 
    'password' => 'passuser1', 
    'gender' => 1, 
]; 
1

請嘗試通過這樣的

$data_string = '{"apple": "fruit", "turnip": "vegetable"}';                        
$ch = curl_init('http://requestb.in/13zghda1');                  
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                  
curl_setopt($ch, CURLOPT_POSTFIELDS, array('data' => $data_string));                 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                           
$result = curl_exec($ch); 

也請檢查響應上https://requestb.in/13zghda1?inspect 在後端,你將得到的數據現在

+0

我需要發送JSON輸入與捲曲請求..和捲曲帖子字段期望一個字符串不是一個PHP數組。 –

+0

您需要爲json使用標頭。首先轉換數組JSON '$ data_string = json_encode($的數據);' 之後,你就可以對JSON設定的設置 ' curl_setopt($ CH,CURLOPT_HTTPHEADER,陣列( 「內容類型:應用程序/ json', 'Content-Length:'。strlen($ data_string)) ); ' –

+0

我這樣做,請看看整個方法。 –

0

如果你想發佈一個數組($ data),試試這個:

$data = ['apple' => 'fruit', 'turnip' => 'vegetable']; 
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); 
+0

需要發送json而不是表單編碼數據。 –

+0

@MubasharAbbas爲什麼你嚴格要發送JSON而不是在接收端創建JSON? – apokryfos

0

所以事實證明,在花了兩天的時間後,在調用這個方法時,我傳遞了第三個參數(頭文件),一個令牌,其末尾有\n(錯誤地)對於那個角色,請求主體正在被截斷。

我不知道爲什麼,但刪除那\n修復它。

因此,在未來,如果有人跑入的情況,你的

捲曲請求主體沒有被髮送或者被截斷

然後

看看到請求標頭對於那些不應該在那裏的特殊字符。