2016-08-16 66 views
1

我試圖將數據發送到外部休息API調用,他們以原始格式獲取數據。PHP - 如何將身體設置爲捲曲原始狀態

這是我的代碼:

$headers = array('Authorization: XXXXXX', 'Content-Type: application/json'); 
$data = array('name' => 'test', 'age' => 26); 
$post['data'] = json_encode($data); 
$url = 'My external api url'; 
$process = curl_init(); 
curl_setopt($process, CURLOPT_TIMEOUT, 600000); 
curl_setopt($process, CURLOPT_HEADER, 0); 
curl_setopt($process, CURLOPT_HTTPHEADER, $headers); 
curl_setopt($process, CURLOPT_URL, $url); 
curl_setopt($process, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1); 
curl_setopt($process, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); 
curl_setopt($process, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); 

$user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.7 ' . 
    '(KHTML, like Gecko) Chrome/7.0.517.41 Safari/534.7'; // imitate chrome 
curl_setopt ($process, CURLOPT_USERAGENT, $user_agent); 

if ($method == 'POST') { 
    curl_setopt($process, CURLOPT_POST, 1); 
    curl_setopt($process, CURLOPT_POSTFIELDS, $data); 
} 
elseif ($method == 'PUT') { 
    curl_setopt($process, CURLOPT_CUSTOMREQUEST, "PUT"); 
    curl_setopt($process, CURLOPT_POSTFIELDS, http_build_query($data)); 
} 

$response = curl_exec($process); 
print_r($response);exit; 

它給出了一個空的響應。當我在REST API附加組件中嘗試這個時,它會給出正確的結果。

我想知道如何將form body設置爲原始類型,如表單數據,二進制& x-www-form-urlencoded?

請參考附圖片:

enter image description here

答: 我試圖通過輸入JSON格式。它爲我工作。 這是樣品輸入:

{ "data":{ "name": "test", "age": 26 } } 
+0

如果你傳遞一個數組捲曲的POSTFIELDS,然後捲曲將數組轉換成WWW的形式。傳遞一個字符串,curl會讓它獨立出來,因爲它會假設你已經做了任何必要的事情來將該字符串格式化爲接收者所期望的。 –

+0

我試過了,但它仍然返回一個空的回覆 – Guru

+0

你確定它是空的? curl_exec在失敗時返回布爾值false,print_r將作爲零長度字符串吐出。做'$ response = curl_exec(...); if($ response === false){die(curl_error($ process));而不是。 –

回答

-1

試試這個: curl_setopt($process, CURLOPT_HTTPHEADER, array('Content-Type: text/plain'));