2016-12-29 4 views
-1

Slim Framework 3の新機能です。私はApi Keyヘッダー値を持つWebサービスにアクセスする際に問題があります。 Api Keyの価値があり、JSONデータを取得するためにWebサービスにアクセスしたいと思っています。ここに私のスリムgetメソッドのコードです:私はポストマン(クロームアプリ)でWebサービスを試してみましたSlim Framework 3の複数のヘッダー値をapiキーを使用してWebサービスに設定するにはどうすればよいですか?

$app->get('/getbooking/{id}', function (Request $request, Response $response, $args) { 
    $id = $args['id']; 
    $string = file_get_contents('http://maindomain.com/webapi/user/'.$id); 


    //Still confuse how to set header value to access the web service with Api Key in the header included. 
}); 

アクセスすると、私は結果を得ます。私はGETメソッドを使用し、Api Keyのヘッダ値を設定します。

しかし、Slim 3でヘッダーの値を設定してWebサービスにアクセスするにはどうすればいいですか?

ありがとうございます。

+0

私はここアリンPurcaruの答えはあなたに参考になると思いますhttp://stackoverflow.com/questions/35439409/how-do-i-set-a-json-header-in-slim -3-framwork-php – Veerendra

+0

'' http://maindomain.com/webapi/user /'.$ id' urlリクエストにカスタムヘッダを設定したいのですか? –

答えて

2

これは実際にSlimとは関係ありません。 PHP内からストリーム(file_get_contents())、curl、ライブラリ(Guzzleなど)を含むHTTPリクエストを行う方法は複数あります。

あなたの例ではfile_get_contents()を使用しています。したがって、ヘッダを設定するには、コンテキストを作成する必要があります。このような何か:

$app->get('/getbooking/{id}', function (Request $request, Response $response, $args) { 
    $id = $args['id']; // validate $id here before using it! 

    // add headers. Each one is separated by "\r\n" 
    $options['http']['header'] = 'Authorization: Bearer {token here}'; 
    $options['http']['header'] .= "\r\nAccept: application/json"; 

    // create context 
    $context = stream_context_create($options); 

    // make API request 
    $string = file_get_contents('http://maindomain.com/webapi/user/'.$id, 0, $context); 
    if (false === $string) { 
    throw new \Exception('Unable to connect'); 
    } 

    // get the status code 
    $status = null; 
    if (preg_match('@HTTP/[0-9\.]+\s+([0-9]+)@', $http_response_header[0], $matches)) { 
     $status = (int)$matches[1]; 
    } 

    // check status code and process $string here 
} 
関連する問題