curl post表单数据不起作用

时间:2016-06-13 10:38:20

标签: php curl

我想将表单数据发布到服务但是它显示了表单参数的一些错误,这是我的curl脚本示例:

<?php 
//       header('Content-Type:application/json');

       $data = array();
       $data = json_decode(file_get_contents('php://input'), true);


       $user= $data["username"];
       $pass= $data["password"];


       $form_data = array('username' => $user, 'password' => $pass);
       $url = "http://localhost:8585/auth/session";


       $ch = curl_init();
       curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
       curl_setopt($ch, CURLOPT_URL, $url);
       curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
       curl_setopt($ch, CURLOPT_TIMEOUT, 75);
       curl_setopt($ch, CURLOPT_POST, 1);
       curl_setopt($ch, CURLOPT_POSTFIELDS, $form_data);

       $result = curl_exec($ch);
       curl_close($ch);

       echo "result $result";

在服务网站上产生如下错误:

@FormParam is utilized when the content type of the request entity is not application/x-www-form-urlencoded

1 个答案:

答案 0 :(得分:1)

替换此行

curl_setopt($ch, CURLOPT_POSTFIELDS, $form_data);

这一行

curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($form_data));

您收到错误的原因是您正在发送一个数组,但您需要发送的是一个urlencoded字符串。请参考:                http://php.net/manual/en/function.http-build-query.php