客户端使用PHP,请求JAVA服务端,遇到中文编码问题,JAVA收到的参数中文乱码,以下是请求方法:
$options = ['pageNum' => $page, 'pageSize' => $pageSize, 'name' => $keyword];
$client = new Client([
'timeout' => 60,
'headers' => [
'Content-Type'=>'application/x-www-form-urlencoded;charset=UTF-8',
'enctype'=>'multipart/form-data',
'X-Requested-With' => 'XMLHttpRequest',
],
]);
$response = $client->request('POST', env('DL_URL').$this->packages_url, [
'form_params' => $options,
]);
$body = $response->getBody();
$result = $body->getContents();
header头部有指定UTF-8编码方式,文件也用UTF-8编码,JAVA端也同样使用UTF-8编码,那么JAVA端接收到的中文乱码是怎么回事呢?
以下是解决方法:
$options = ['pageNum' => $page, 'pageSize' => $pageSize, 'name' => $keyword];
$client = new Client([
'timeout' => 60,
]);
$response = $client->request('POST', env('DL_URL').$this->packages_url, [
'form_params' => $options,
//将header头信息加到request方法里
'headers' => [
'Content-Type'=>'application/x-www-form-urlencoded;charset=UTF-8',
'enctype'=>'multipart/form-data',
'X-Requested-With' => 'XMLHttpRequest',
],
]);
$body = $response->getBody();
$result = $body->getContents();
最后,JAVA成功接受到中文,并成功响应。
GuzzleHttp中文文档:GuzzleHttp中文文档