4

Zend\Http\Request と Zend\Http\Client を使用して次のリクエストを作成しています

        //Creating request and client objects
        $request = new Request();
        $client = new Client();

        //Preparing Request Object
        $request->setMethod('POST');
        $request->setUri('https://my.api.address.com/apiendpointurl1234');
        $request->getHeaders()->addHeaders(array(
            'cache-control' => 'no-cache',
            'content-type' => 'application/json',
            'client_secret' => 'asdfasdfasdfasdfasdf',
            'client_id' => 'asdfasdfasdfasdfasdf',
            'accept' => 'application/json',
            'authorization' => 'Basic MTIzNDoxMjM0',
        ));
        $request->getPost()->set(json_encode(array(
            'student_id' => '123456',
            'short_description' => 'this is short description',
            'description' => 'this is detailed description of the question',
        )));

        //Sending Request
        $response = $client->send($request);

        var_dump( $response->getBody() );

ただし、応答には次のエラーが表示されます。

"エラー": "ヘッダー: client_id が必要です"

Postman 経由で API を突くと、問題なく動作します。しかし、PHP アプリケーションから呼び出すと、ヘッダーが正しく送信されていないことがわかり、上記のエラーが発生します。ヘッダーが送信されない理由を誰でも知っていますか?

4

6 に答える 6

1

これが私のために働いたものです:

//Creating request and client objects
$request = new Request();
$client = new Client();

//Preparing Request Object
$request->setMethod('POST');
$request->setUri('https://my.api.address.com/apiendpointurl1234');
$request->getHeaders()->addHeaders(array(
    'cache-control' => 'no-cache',
    'content-type' => 'application/json',
    'client_secret' => 'asdfasdfasdfasdfasdf',
    'client_id' => 'asdfasdfasdfasdfasdf',
    'accept' => 'application/json',
    'authorization' => 'Basic MTIzNDoxMjM0'
));

$client->setOptions(['strictredirects' => true]);

$request->setContent(json_encode(array(
    'student_id' => '123456',
    'short_description' => 'this is short description',
    'description' => 'this is detailed description of the question',
)));

//Sending Request
$response = $client->send($request);

echo ($response->getBody());

私の仮定は、API から別の URL へのリダイレクトがあり、ヘッダーが reset されることです。Client.php の 943 行目で確認できます。

$this->resetParameters(false, false);

と呼ばれます。Postman はリダイレクトに同じヘッダーを再利用するため、これは Postman では発生しません。

実際には、追加するだけでこれをテストできます

$client->setOptions(['strictredirects' => true]);

これにより、リダイレクト間でヘッダーを保持できるようになります

PS: 上記のコードを最新の安定版の zend http で試してみたところ、「$request->getPost()->set」行でエラーが発生しました。とにかく、これは問題の原因ではありません。

編集: 私の 2 番目の仮定は、"client_id" ヘッダー名が api によって大文字と小文字を区別してクエリされ、エラーが発生することです。リクエストは Zend\Http\Client によって送信されるため、"Zend\Http\Client\Adapter\Socket を使用します。 " 各ヘッダーの最初の文字を大文字にします (361 行目)。したがって、「Client_id」は実際に送信されます。Zend\Http\Client\Adapter\Socket の 361 行目を編集します。

 $v = ucfirst($k) . ": $v";

  $v = $k . ": $v";

ヘッダーが受信されたかどうかをテストします。

于 2017-01-24T09:47:43.960 に答える