2017-04-19 90 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修复它。

因此,在未来,如果有人跑入的情况,你的

卷曲请求主体没有被发送或者被截断

然后

看看到请求标头对于那些不应该在那里的特殊字符。