未找到PHP Symfony curl发布数据

时间:2018-04-25 12:46:55

标签: php symfony curl

我试图将Post数据从symfony项目发送到另一个Symfony项目(用作API)。但数据似乎并没有按照要求进行..

问题似乎来自于在网址更改后需要重新发布的cURL帖子数据。因为如果我删除" curl_setopt($ curl,CURLOPT_FOLLOWLOCATION,1);",则响应是一个html页面,试图刷新所请求的同一页面。

我用'#34; args not found"根据以下代码..

控制器呼叫(项目A)

public function onlineHandlerAction(Request $req, $name, $surname)
{

    $url = $this->getParameter("api"). "avis/find";

    $args = array(
        "name" => "qsdqsdqsd",
        "surname" => $surname,
        "birthdate" => $defunt->getBirthDate()->getTimestamp()
    );

    $apiRes = $kgns->CallAPI('POST', $url, $args);

    var_dump($apiRes);

    return $this->render('**:online-handler.html.twig', array(
        'res' => $apiRes
    ));                                             

}

调用我在网上找到的api函数并编辑我的需要。 (项目A的工具)

public function CallAPI($method, $url, $data = false)
{

    $curl = curl_init();

  switch ($method)
  {
      case "POST":
          curl_setopt($curl, CURLOPT_POST, 1);

          if ($data)
              curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
          break;
      case "PUT":
          curl_setopt($curl, CURLOPT_PUT, 1);
          break;
      default:
          if ($data)
              $url = sprintf("%s?%s", $url, http_build_query($data));
  }

  curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
  curl_setopt($curl, CURLOPT_URL, $url);
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);    
  curl_setopt($curl, CURLOPT_POSTREDIR, 1);

  $result = curl_exec($curl);

  curl_close($curl);

  return $result;

}

api功能(项目B)

public function avisFindAction(Request $req)
{


  $em = $this->getDoctrine()->getManager();

  $args = $req->request->all();

  $argsFound = false;


  if(null !== $args && count($args) > 0):

    $argsFound = true;

    foreach ($args as $key => $value) {
      if($key=='birthdate') $args[$key] = new \DateTime($value);
      else $args[$key] = $value;
    }

    $avis = $em->getRepository('MainBundle:Avis')
                  ->findOneBy($args);

    if($avis):

      $encoders = array(new JsonEncoder());               
      $normalizers = array(new ObjectNormalizer());
      $serializer = new Serializer($normalizers, $encoders);
      $avisJSON = $serializer->serialize($avis, 'json');

      $response = new Response($avisJSON);
      $response->headers->set('Content-Type', 'application/json');
      return $response;

    else:

      $response = ["error"=>"avis not found"];

    endif;

  else:

    $response = ["error"=>"args not found"];

  endif;

  return new JsonResponse(['test'=>'test', 'argsFound'=>$argsFound]);

}

0 个答案:

没有答案