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

时间:2018-03-08 16:51:15

标签: php json curl

我正在尝试将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}

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

1 个答案:

答案 0 :(得分: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);