【问题标题】:How to use Guzzle HTTP Post method如何使用 Guzzle HTTP Post 方法
【发布时间】:2018-07-31 22:26:41
【问题描述】:

我正在Laravel 5.4 中构建一个小型应用程序,我在通过GuzzleHttp 进行API 调用时遇到困难,我试图在我的api.php 中调用route

Route::post('/request', 'HomeController@getRequest');

在我的控制器中我正在调用:

public function __construct(GuzzleHttp\Client $client)
{
    $this->client = $client;
}

public function getRequest( Request $request)
{
    $request = $this->client->post($request->url, [$request->request_data]);
    $response = \GuzzleHttp\json_decode($request->getBody());
    return response()->json(['data' => json_decode($response->d)], $request->getStatusCode());
}

我要插入的数据值集:

{"url":"http://demo.conxn.co.in/CoxnsvcA.svc/Login","request_data":{"username":"********","password":"*******","client_secret_key":"rybbdk23dsaxxmYTHJKFHJSKksdfljsdf"}}

我得到了错误:

但是在通过 postman API 测试器使用时,我得到了适当的结果。

帮我解决这个问题。

【问题讨论】:

    标签: laravel laravel-5 guzzle6 guzzle


    【解决方案1】:

    您以错误的方式发布 JSON 数据,您可以使用内置的 JSON 选项,该选项用于轻松上传 JSON 编码的数据作为请求的正文。如果消息中没有 Content-Type 标头,将添加 application/json 的 Content-Type 标头。

    您可以在这里找到更多详细信息http://docs.guzzlephp.org/en/latest/request-options.html#json

    这是您的更新代码

    public function __construct(GuzzleHttp\Client $client)
    {
    $this->client = $client;
    }
    
    public function getRequest( Request $request)
    {
       $request = $this->client->post($request->url,GuzzleHttp\RequestOptions::JSON =>[$request>request_data]);
       $response = \GuzzleHttp\json_decode($request->getBody());
       return response()->json(['data' => json_decode($response->d)],$request->getStatusCode());
    }
    

    【讨论】:

      【解决方案2】:

      或许你可以试试这个方法

      public function getRequest(Request $request)
          {
            $client = New GuzzleHttpClient();
      
             $input = $request->all();
             unset($input['_token']);
      
      
             //Post to server
             $request = $client->request('POST','url',[
              'form_params' => [
      
             'inputcontent' => $input['inputcontent'],
              ]
              ]);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-10-21
        • 2020-07-19
        • 2022-11-16
        • 2011-10-21
        • 2019-10-12
        • 1970-01-01
        • 2015-08-31
        • 2017-01-11
        相关资源
        最近更新 更多