如何使用Guzzle HTTP Post方法

时间:2018-02-21 11:02:03

标签: laravel laravel-5 guzzle guzzle6 guzzlehttp

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

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"}}

我收到错误:

error description

但在使用postman API测试仪时,我得到了合适的结果。

Appropriate results through postman API checker

帮我解决这个问题。

2 个答案:

答案 0 :(得分:0)

您以错误的方式发布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());
}

答案 1 :(得分:0)

也许你可以试试这个方法

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'],
        ]
        ]);
相关问题