简体   繁体   English

Laravel使用正确的编码获取请求主体

[英]Laravel get request body with correct encoding

The function is simple, I need to forward a post request to an external API service. 功能很简单,我需要将发布请求转发到外部API服务。 I am using Laravel 5.5 and the $client is Guzzle 6 client; 我正在使用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){
      .....
    }
}

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

the data send to laravel is [{"name":"Secion4小明","comment":"","applicationId":"59"}] 发送到laravel的数据是[{“ name”:“ Secion4小明”,“ comment”:“”,“ applicationId”:“ 59”}]

the data received by the external API is [{"name":"Secion4\小\明","comment":null,"applicationId":"59"}] 外部API接收的数据为[{“ name”:“ Secion4 \\ u5c0f \\ u660e”,“ comment”:null,“ applicationId”:“ 59”}]

If i change the code to 如果我将代码更改为

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

the external API received the data as [{\\"name\\":\\"Secion4\小\明\\",\\"comment\\":\\"\\",\\"applicationId\\":\\"59\\"}] 外部API接收的数据为[{\\“ name \\”:\\“ Secion4 \\ u5c0f \\ u660e \\”,\\“ comment \\”:\\“ \\”,\\“ applicationId \\”:\\“ 59 \\”}]

How can I make the encoding correct? 如何使编码正确? I Can't find the way to set the encoding. 我找不到设置编码的方法。

Update 1: 更新1:

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

External API got [{\\"name\\":\\"Secion4??\\",\\"comment\\":\\"\\",\\"applicationId\\":\\"59\\"}] 外部API得到了[{\\“ name \\”:\\“ Secion4 ?? \\”,\\“ comment \\”:\\“ \\”,\\“ applicationId \\”:\\“ 59 \\”}]

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM