2012-12-08 76 views
0

請不要在閱讀我的實際問題之前關閉此問題。我看到很多相關的問題,但我仍然有。 只需要在PHP中使用CURL通過POST發送json_encoded數組。當我設置content-type as application/json時,數據不會發布。我收到空的post陣列。當我刪除內容類型的行數據發佈,但不是json。 這裏是我的代碼Json加帖子加上curl在PHP中

$data = array('id' => $post['id'], 'action' => $post['action']); 
$post_data = http_build_query($data); 
curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); 
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_data)); 

我這種情況下,我收到空的帖子。如果我註釋掉這一行curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));,我將收到發佈數據,但未收到json編碼。我想要json_encoded數組。有人會告訴我我做錯了什麼?

問候:

+0

你確定目標資源可以讓你請求的響應格式? – Madbreaks

+0

我正在向其他控制器發送請求。我如何才能知道目標資源是否允許? –

回答

1

你編碼查詢字符串JSON不是一個數組中刪除$post_data = http_build_query($data);並通過$data到json_encode。

$data = array('id' => $post['id'], 'action' => $post['action']); 
curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); 
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); 

ofcourse for this service work nedds to support json posts。

+0

當我刪除'http_build_query($ data)'時,即使不發送請求。空郵件 –

+0

什麼意思是'服務nedds支持json posts.'?我怎麼才能知道支持與否? –

+0

@AwaisQarni使用'json_decode(file_get_contents(「php:// input」),true)'獲取發佈的數據。 – Musa

1

嘗試發送正接受RAW POST請求,通過

<?php $postdata = file_get_contents("php://input"); ?> 

RAW POST

+0

那是行得通的。 +1 –