【问题标题】:Guzzle and Unable to parse response into JSONGuzzle 并且无法将响应解析为 JSON
【发布时间】:2013-09-26 00:34:54
【问题描述】:

我有一个使用这种方法的小 php api 客户端:

private function send($endpoint)
{
    $headers = array();
    $body = $this->xmlSerialiser->convertToXML($this->getQueue());

    try {
        $response = json_decode(
            $this->guzzleClient->post(
                $endpoint,
                $headers, $body
            )
            ->send()
            ->json()
        );

    } catch (\Guzzle\Http\Exception\BadResponseException $e) {
        $response = array('Error' => $e->getMessage());
    }

    return $response;
}

我总是收到

Unable to parse response body into JSON: 4 (500 Internal Server Error)

我已经尝试了解服务器响应的示例,并且似乎很好:

echo (string) $this->guzzleClient->post(
                $endpoint,
                $headers, $body
            )
            ->send()->getBody();

结果如下:

<Messages xmlns="http://www.example.com/xxx/3.0">

<GetAccountResponse RequestType="GetAccount">

    <AccountId>xxxx-xxx-xxx-xxxx-xxxx</AccountId>

    <Token>xxxxxxxxxxxxxx/t3VkEJXC7f6b6G4yPJSZ5QfT2hdSQXUmi0e8cndSYLK4N7mswRHifzwGHLUJYHM17iGL8s=</Token>

</GetAccountResponse>

【问题讨论】:

    标签: php xml json guzzle


    【解决方案1】:

    我自己回答了

    Guzzle 文档说:json 方法 -> 解析 JSON 响应正文并返回一个数组

    所以在我的情况下,我需要将 json 方法切换为 xml(因为响应是 xml)。

    最后是这样的结果:

    private function send($endpoint)
    {
        $headers = array();
        $body = $this->xmlSerialiser->convertToXML($this->getQueue());
    
        try {
            $response = (array)(
                $this->guzzleClient->post(
                    $endpoint,
                    $headers, $body
                )
                ->send()
                ->xml()
            );
        } catch (\Guzzle\Http\Exception\BadResponseException $e) {
            $response = array('Error' => $e->getMessage());
        }
    
        return $response;
    }
    

    【讨论】:

    • 你可以使用 $response->getBody()->getContents()
    【解决方案2】:

    使用以下代码。

     $response->getBody()->getContents() 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-19
      • 1970-01-01
      • 1970-01-01
      • 2016-01-16
      • 1970-01-01
      相关资源
      最近更新 更多