通过php curl发送json但没有得到回复

问题描述 投票:1回答:1

我正在尝试将json发送到网址并获得回复。我相信我正确地创造了json。但是当我尝试通过php curl发送它时,我没有得到回复。我发送给它的网址确实填充了一个回复。

这是php:

<?php
    $post = array("prompt" => $question, "functionName" => $func_name, "argumentNames" => $argumentNames, "testCases" => $testCases);

    $transfer = json_encode($post);   


    $ctrl = curl_init();
    curl_setopt($ctrl, CURLOPT_URL, "https://sample.com/question/add-question.php");
    curl_setopt($ctrl, CURLOPT_POST, TRUE);
    curl_setopt($ctrl, CURLOPT_POSTFIELDS, $transfer);
    curl_setopt($ctrl, CURLOPT_RETURNTRANSFER, TRUE);
    $response = curl_exec($ctrl);
    curl_close($ctrl);
    $response = json_decode($response);

    echo $response;
?>

如果我要回复$ transfer,它会显示:

{
"prompt":"Write a function named test that takes 2 argument(s) and adds them. The type of the arguments passed into the function and the value to be returned is int. The arguments for the function should be arg1 and arg2 depending on the number of arguments the function needs.",
"functionName":"test",
"argumentNames":["arg1","arg2"],
"testCases":{"input":["2","2"],
             "output":"4"}
}

我想回应来自我发送json的网址的响应,但相反,我什么也得不回来。然而,卷曲序列中的url(https://sample.com/question/add-question.php)确实在网页上输出了一个json:

{"message":"An unknown internal error occured","success":false}

我怎么能抓住这个并在原始代码片段中回显它?我的卷曲方法有问题吗?

php json curl
1个回答
2
投票

尝试设置标题,表示您正在发送JSON ...

curl_setopt($ctrl, CURLOPT_HTTPHEADER, array(                                                                          
    'Content-Type: application/json',                                                                                
    'Content-Length: ' . strlen($transfer))                                                                       
); 

对于HTTPS,您可能还需要......

curl_setopt($ctrl, CURLOPT_SSL_VERIFYPEER, false);

你也可以试试......

curl_setopt($ctrl, CURLOPT_FOLLOWLOCATION, 1); 
© www.soinside.com 2019 - 2024. All rights reserved.