PHP - 如何将身体设置为卷曲原始状态

问题描述:

我试图将数据发送到外部休息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));而不是。 –

试试这个: curl_setopt($process, CURLOPT_HTTPHEADER, array('Content-Type: text/plain'));