Запрос POST Guzzle 6 дает несанкционированный ответ 401

Это код, который я использую для одновременной отправки нескольких запросов на жужжание.

<?php
    //initialize test values.
    $results = [];
    $smpUrls = [];
    $client  = new Client();
    $authHeader = [
        'cookies' => true,
        'auth'    => [$this->username, $this->password],
        'json'    => [
            "alert" => 'test title',
            "data"  => 'test data sample'
        ],
        'debug' => true,
        'headers' => [
            'Content-Type'  => 'application/json',
            'Cache-Control' => 'no-cache',
            'X-SMP-DATA'    => 'testng'
        ],
    ];
    $technicianIds = ["123456"];


    //preparing urls
    foreach ($technicianIds as $technicianId) {
        $smpUrl = 'http://10.11.1.5:8080/restnotification/application/com.****.test/user/' . $technicianId;
        $smpUrls[$technicianId] = $smpUrl;

    }

    //generate function to deal with multiple requests.
    $requests = function ($urls, $headers) {
        foreach ($urls as $url) {
            yield new Request('POST', $url, $headers);
        }
    };

    /**
     * initialize guzzle pool in order to deal with individual request
     * response or exception
     */
    $pool = new Pool($client, $requests($smpUrls, $authHeader), [

        //process only four requests cuncurently.
        'concurrency' => 4,

        //deal with succesful request response.
        'fulfilled' => function ($response, $index) use (&$results) {
            //json decode output, collect name and append to result.
            \Log::info('fullfilled-response');
            \Log::info($response);
        },

        //deal with exception of individual request.
        'rejected' => function ($reason, $index) use (&$results) {
            \Log::info('rejected-reason');
            \Log::info($reason);
        }
    ]);

    // Initiate the transfers and create a promise
    $promise = $pool->promise();

    // Force the pool of requests to complete.
    $promise->wait();

    return $results;

Но это дает мне сообщение об ошибке ниже.

Ошибка клиента: POST http://10.11.1.5:8080/restnotification/application/com.*****.test/user/123456 привела к 401 Unauthorized ответу

Однако, если я отправлю тот же запрос через почтальона с правильными учетными данными, похоже, он работает.

Пожалуйста, просмотрите сгенерированные данные запроса guzzle ниже.

GuzzleHttp\Psr7\Request Object
(
    [method:GuzzleHttp\Psr7\Request:private] => POST
    [requestTarget:GuzzleHttp\Psr7\Request:private] => 
    [uri:GuzzleHttp\Psr7\Request:private] => GuzzleHttp\Psr7\Uri Object
        (
            [scheme:GuzzleHttp\Psr7\Uri:private] => http
            [userInfo:GuzzleHttp\Psr7\Uri:private] => 
            [host:GuzzleHttp\Psr7\Uri:private] => 10.11.1.5
            [port:GuzzleHttp\Psr7\Uri:private] => 8080
            [path:GuzzleHttp\Psr7\Uri:private] => /restnotification/application/com.*****.test/user/dileep
            [query:GuzzleHttp\Psr7\Uri:private] => 
            [fragment:GuzzleHttp\Psr7\Uri:private] => 
        )

    [headers:GuzzleHttp\Psr7\Request:private] => Array
        (
            [User-Agent] => Array
                (
                    [0] => GuzzleHttp/6.2.1 curl/7.50.1 PHP/7.0.10
                )

            [Host] => Array
                (
                    [0] => 10.11.1.5:8080
                )

            [cookies] => Array
                (
                    [0] => 1
                )

            [auth] => Array
                (
                    [0] => ******
                    [1] => ******
                )

            [json] => Array
                (
                    [alert] => Test Title
                    [data] => test details testing
                )

            [debug] => Array
                (
                    [0] => 1
                )

            [headers] => Array
                (
                    [Content-Type] => application/json
                    [Cache-Control] => no-cache
                    [X-SMP-DATA] => testng
                )

        )

    [headerNames:GuzzleHttp\Psr7\Request:private] => Array
        (
            [user-agent] => User-Agent
            [host] => Host
            [cookies] => cookies
            [auth] => auth
            [json] => json
            [debug] => debug
            [headers] => headers
        )

    [protocol:GuzzleHttp\Psr7\Request:private] => 1.1
    [stream:GuzzleHttp\Psr7\Request:private] => GuzzleHttp\Psr7\Stream Object
        (
            [stream:GuzzleHttp\Psr7\Stream:private] => Resource id #378
            [size:GuzzleHttp\Psr7\Stream:private] => 0
            [seekable:GuzzleHttp\Psr7\Stream:private] => 1
            [readable:GuzzleHttp\Psr7\Stream:private] => 1
            [writable:GuzzleHttp\Psr7\Stream:private] => 1
            [uri:GuzzleHttp\Psr7\Stream:private] => php://temp
            [customMetadata:GuzzleHttp\Psr7\Stream:private] => Array
                (
                )

        )

)

Что я здесь делаю не так? Пожалуйста, поделитесь своими мыслями. Спасибо.


person Rajeev K Tomy    schedule 21.07.2017    source источник


Ответы (1)


К сожалению, мне не удалось устранить эту ошибку. Похоже, в моем случае метод обещаний не работает.

Итак, что я сделал, так это перебрал сообщение с жужжанием по циклу. В моем случае пост Guzzle работает без проблем.

Пример кода, который работал в моем случае, приведен ниже:

<?php
//initialize test values.
$results = [];
$smpUrls = [];
$client  = new Client();
$authHeader = [
    'cookies' => true,
    'auth'    => [$this->username, $this->password],
    'json'    => [
        "alert" => 'test title',
        "data"  => 'test data sample'
    ],
    'debug' => true,
    'headers' => [
        'Content-Type'  => 'application/json',
        'Cache-Control' => 'no-cache',
        'X-SMP-DATA'    => 'testng'
    ],
];
$technicianIds = ["123456"];


//preparing urls
foreach ($technicianIds as $technicianId) {
    $smpUrl = 'http://10.11.1.5:8080/restnotification/application/com.****.test/user/' . $technicianId;
    $results[] = $client->post($smpUrl, $authHeader);

}
return $results;
person Rajeev K Tomy    schedule 13.08.2017