GuzzleHttp无法发送JSON,返回错误500,Curl工作正常

时间:2019-05-28 06:57:43

标签: json guzzle http-status-code-500

我尝试使用Guzzle发送查询:

    $client = new \GuzzleHttp\Client(['http_errors' => false]);
    $response = $client->request('POST', 'https://myserwer.com/sendQuery', [
        'headers' => [
            'Authorization' => 'Bearer ' . $access_token,
            'Content-Type' => 'application/json',
            'Accept' => 'application/json',
        ],
        ['json' => ["username" => "cxzczxc", "firstName" => "dsadascxzc", "lastName" => "dsadascxzc", "email" => "dsadascxzc@wp.pl","enabled" => "true"]]
    ]);

    $status = $response -> getStatusCode();

    if ($status === 201) {
        return response()->json("Register user OK", 200);
    } else {
        return "error_code: " . $status;
    }

我使用此answer转换JSON。 documencation 中也是如此:

$response = $client->request('PUT', '/put', ['json' => ['foo' => 'bar']]);

但是Guzzle返回错误:500:

  

服务器错误:POST https://myserwer.com/sendQuery导致500 Internal Server Error响应

所以我用了CURL

$curl = curl_init();

curl_setopt_array($curl, array(
    CURLOPT_URL => "https://myserwer.com/sendQuery",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_POSTFIELDS => "{\"username\":\"cxzczxc\",\"firstName\":\"dsadascxzc\",\"lastName\":\"dsadascxzc\",\"email\":\"dsadascxzc@wp.pl\",\"enabled\":\"true\"}",
    CURLOPT_HTTPHEADER => array(
    "authorization: Bearer " . $access_token,
    "content-type: application/json"
    ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
    return "error_code: " . $err;
} else {
    return response()->json("Register user OK", 200);
}

此代码正常工作。 为什么Guzzle无法发送查询?

0 个答案:

没有答案