Laravel获取具有正确编码的请求正文

时间:2018-01-26 14:04:08

标签: php json laravel rest encoding

功能很简单,我需要将post请求转发给外部API服务。我使用的是Laravel 5.5,$ client是Guzzle 6客户端;

use Illuminate\Http\Request;
use GuzzleHttp\Client; 

public function insert(Request $request)
{
    try {
        $body =  $request->json()->all();
        $response = $this->client->post($this->generateUrl("/api/sections?", $request->getQueryString()), ['json' =>$body]);
        return response($response->getBody(),$response->getStatusCode())>withHeaders($response->getHeaders());
    }catch(Exception $e){
      .....
    }
}

问题是$ bodyStringRAW = $ request-> json() - > all();

发送到laravel的数据是  的 [{"名称":" Secion4小明""评价":"""的applicationID&#34 ;:" 59"}]

外部API收到的数据是 [{" name":" Secion4 \ u5c0f \ u660e"," comment":null,& #34;的applicationID":" 59"}]

如果我将代码更改为

$response = $this->client->post($this->generateUrl("/api/sections?", $request->getQueryString()), ['json' =>$request->getContent()]);

外部API接收数据为 的 [{\"名称\":\" Secion4 \ u5c0f \ u660e \" \"评论\":\" \" \"的applicationID \":\" 59 \"}]

如何使编码正确?我无法找到设置编码的方法。

更新1:

 $body =  utf8_decode($request->getContent());
 $response = $this->client->post($this->generateUrl("/api/sections?", $request->getQueryString()), ['json' =>$body]);

获得外部API [{\"名称\":\" Secion4 ?? \" \"评论\":\" \" ,\"的applicationID \":\" 59 \"}]

1 个答案:

答案 0 :(得分:0)

数据是Unicode,您可以使用utf8_decode进行转换。