2014-05-09 3 views
0

Play Framework로 개발 된 웹 응용 프로그램이 제공되었습니다. 그들은 서비스로 불릴 수 있고 그것의 자신의 API를 가지고 있다고 말했다.PHP로 Play Framework API 호출

파일이 있지만 Play Framework에 대해 전혀 알지 못합니다. 그들은 다음과 같은 파일을 확인하라고 말했습니다 :

# Authentication 
POST  /api/v1/session.json            controllers.base.Application.keepAlive() 
DELETE /api/v1/session.json            controllers.base.Application.logout() 
POST  /api/v1/session/login.json           controllers.base.Application.login(redirectTo: String ?= null, isGuest: Boolean ?= false) 

나는이 서비스를 PHP와 함께 부르고 싶습니다. 가능한가? Play Framework를 사용하여 호출해야합니까?

나는 Play에 대해 아무 것도 모릅니다.

$data = array("redirectTo" => "", "isGuest" => true); 

$url = 'http://localhost:9000/api/v1/session/login.json'; 

$options = array(
    'http' => array(
    'method' => 'POST', 
    'content' => json_encode($data), 
    'header'=> "Content-Type: application/json\r\n" . 
       "Accept: application/json\r\n" 
    ) 
); 

$context = stream_context_create($options); 
$result = file_get_contents($url, false, $context); 
$response = json_decode($result); 

하지만 PHP는 말한다 : 나는 같이 호출하려고

Warning: file_get_contents(http://localhost:9000/api/v1/session/login.json?redirectTo=''&isGuest=true): failed to open stream: HTTP request failed! 

응용 프로그램 내 로컬 시스템에서 실행됩니다.

감사합니다.

+0

경고는 url이 사실이 아니라고 말합니다. 브라우저에서 http : // localhost : 9000/api/v1/session/login.json으로 이동하면 어떤 결과가 발생합니까? 그리고 url의 끝에 추가 한 params는 사실입니까? 그리고 POST 핸들러에 요청을합니다. –

+0

내 API 호출을 편집하여 스트림 경고를 열지 못했습니다. 브라우저에서 호출 할 때 GET에 대한 작업이 없습니다.라는 메시지가 표시됩니다. 하지만 지금 나는 POST로하고있다. – Ataman

+0

php-curl로 할 수 있습니다. 내 대답보기 [여기] (http://stackoverflow.com/questions/23564811/calling-play-framework-api-by-php/23565054#23565054) –

답변

1

커스텀 기능으로 해당 서비스에 컬 요청을 할 수 있습니다.

/** 
* @url your api url 
* @method POST,GET,DELETE 
* @params if your request method post, you can send array with key=>value 
* 
*/ 
function callApi($url, $method, $params = null) { 
    //open connection 
    $ch = curl_init(); 
    curl_setopt($ch,CURLOPT_URL, $url); 
    if ($method == "POST") { 
     foreach($params as $key=>$value) { 
      $fields_string .= $key.'='.$value.'&'; 
     } 
     rtrim($fields_string, '&'); 

     curl_setopt($ch,CURLOPT_POST, count($params)); 
     curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string); 
    } else if ($method == "GET") { 

    } else if ($method == "DELETE") { 
     curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE"); 
    } else { 
     return false; 
    } 

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
    //execute post 
    $result = curl_exec($ch); 

    //close connection 
    curl_close($ch); 

    return $result; 
} 

예제 사용법;

callApi("http://localhost:9000/api/v1/session/login.json", "POST", array("username" => "john", "password" => "ssshhh")); //POST 
callApi("http://localhost:9000/api/v1/session.json", "DELETE"); // DELETE