【问题标题】:How to send 'list' json request when using Guzzle?使用 Guzzle 时如何发送“列表”json 请求?
【发布时间】:2017-02-14 19:19:07
【问题描述】:

我正在使用 Guzzle 为服务器编写 php sdk,我想使用 Guzzle 发送这样的 http json 正文:

["test_1","test_2"]

但是当我写这段代码的时候,我得到了错误的json:

$body = array(
    'test_1',
    'test_2',
);
$guzzleRequest = guzzleClient->createRequest(
        $httpMethod,
        $url,
        $headers,
        $body,
        $guzzleRequestOptions
);
$guzzleResponse = $this->guzzleClient->send($guzzleRequest);

我将这个错误的 json 发送到服务器。

{"0":"test_1","1":"test_2"}

那么,我的问题是如何使用 Guzzle 发送 JSON 正文,如列表?

【问题讨论】:

    标签: php json guzzle


    【解决方案1】:

    尝试使用:

    $guzzleRequest = guzzleClient->createRequest(
        $httpMethod,
        $url,
        $headers,
        json_encode($body),
        $guzzleRequestOptions
    );
    

    【讨论】:

      【解决方案2】:

      此代码适用于我通过 Guzzle 发送 json

      use GuzzleHttp\Client;
      // url destination 
      $url = 'http://127.0.0.1:8080';
      // headers , if the api dosen't require access token you can remove Authorization from header
      $headers = [
          'Accept' => 'application/json',
          'Authorization' => "bearer ".$access_token
      ];
      // body
      $body = [
          '1' => 'test1',
          '2' => 'test2'
      ];
      // init Guzzle
      $client = new client();
      // init Guzzle
      $response = $client->post($url , [
          'headers' => $headers, 
          'json' => $body,
      ]);
      
      $status_code = $response->getStatusCode(); // 200
      $status_message = $response->getReasonPhrase(); // ok
      

      【讨论】:

        猜你喜欢
        • 2014-04-10
        • 2022-02-21
        • 2019-12-12
        • 1970-01-01
        • 2018-02-07
        • 2017-08-28
        • 2020-07-14
        • 1970-01-01
        • 2020-02-08
        相关资源
        最近更新 更多