You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP Client调用PUT接口返回乱码,Postman测试正常问题排查

问题解决思路

1. 修正请求头的定义顺序

你的代码里$headers变量是在调用setHeaders()之后才定义的,这会导致实际发送的请求头为空或无效值,这很可能是乱码的核心原因之一。必须先定义请求头再设置到Client中:

$headers = [
  'Authorization' => "************************",
  'Content-Type' => 'application/json',
  'Accept' => 'application/json',
  'Accept-Charset' => 'UTF-8'
];

$client = new Client();
$client->setMethod('PUT');
$client->setUri($uri);
$client->setHeaders($headers);
$client->setRawBody(json_encode($body));
$response = $client->send();
$responseContent = $response->getContent();

2. 处理响应的编码与压缩

如果服务端返回gzip压缩内容但Client未自动解压,会直接出现乱码。可通过两种方式处理:

方法一:启用Client自动解压(以Guzzle为例)

若使用Guzzle Client,创建实例时开启自动解压配置:

$client = new Client([
    'decode_content' => true,
]);

方法二:手动检测并解压响应

如果Client不支持自动解压,可通过响应头判断后手动处理:

$response = $client->send();
$responseContent = $response->getContent();

// 检查是否为gzip压缩格式
if ($response->getHeaderLine('Content-Encoding') === 'gzip') {
    $responseContent = gzdecode($responseContent);
}

// 强制转成UTF-8编码
$responseContent = mb_convert_encoding($responseContent, 'UTF-8', mb_detect_encoding($responseContent));

3. 验证JSON解析有效性

最后可通过解析JSON确认是否解决编码问题:

try {
    $data = json_decode($responseContent, true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        echo 'JSON解析错误: ' . json_last_error_msg();
    } else {
        // 处理正常JSON数据
        var_dump($data);
    }
} catch (Exception $e) {
    echo '处理错误: ' . $e->getMessage();
}

内容的提问来源于stack exchange,提问作者Scrooge

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 07:40:38