【问题标题】:Using Guzzle 6 in Laravel to communicate with an external API在 Laravel 中使用 Guzzle 6 与外部 API 进行通信
【发布时间】:2018-03-08 07:22:30
【问题描述】:

当我在命令行上执行此操作时:

curl -X POST -d '{"userDetails":{"username":"myself","password":"Myself123"}}' https://sub.domain.com/energy/api/login

它像预期的那样返回一个 sessionid。

当我在 Laravel 5.5 上使用 Guzzle 6 并执行以下操作时:

$client = new GuzzleHttp\Client();
    $login = $client->post('https://sub.domain.com/energy/api/login', [
        'userDetails' => [
            'username' => 'myself',
            'password' => 'Myself123'
        ]
 ]);

我收到此错误:

Server error: `POST https://sub.domain.com/energy/api/login` resulted in a `503 Service Unavailable` response: org.json.JSONException: JSONObject["userDetails"] not found.

我做错了什么?

【问题讨论】:

标签: php laravel curl guzzle6


【解决方案1】:

使用它来调试和发送请求,示例在这里。

 include these in class
//FOR GUZZLE
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Exception\ServerException;
use GuzzleHttp\Exception\BadResponseException;
use GuzzleHttp\Exception\ClientException;


try{
        $endPoint = "http://server_ip/security/subject";
        $options = [ "auth" =>  [$username, $password], "headers" => ["header1" => value, "header2" => value] ];

        $client         = new Client();
        $response       = $client->get($endPoint, $options);
        $responseArray   = json_decode($response->getBody()->getContents(), true);
        $status = $response->getStatusCode();



    }catch(BadResponseException $e){

        $response           = $e->getResponse();
        $reason             = $response->getReasonPhrase();
        $exceptionMessage   = (!empty($reason)) ? $reason. ' email or password.' : 'Unauthorized email or password.';

    }

【讨论】:

    【解决方案2】:

    您没有作为 json 传递。试试这个:

    $req = [
        'userDetails' => [
            'username' => 'myself',
            'password' => 'Myself123'
        ]
    ];
    
    $client = new GuzzleHttp\Client();
    $login = $client->post('https://sub.domain.com/energy/api/login',
        [
            'json' => $req
        ]
    );
    return $login;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-20
      • 2020-01-10
      • 1970-01-01
      • 2018-04-09
      • 1970-01-01
      • 2016-11-01
      • 1970-01-01
      • 2017-06-08
      相关资源
      最近更新 更多