簡體   English   中英

通過php curl發送json但沒有得到響應

[英]sending json via php curl but not getting a response

我正在嘗試將json發送到url並獲得響應。 我相信我正確地創建了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中響應,但是我什么也沒回來。 但是curl序列中的URL( https://sample.com/question/add-question.php )確實在網頁上輸出了json:

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

我如何無法抓住它並在原始代碼片段中回顯它? 我的curl方法有問題嗎?

嘗試設置標頭以說您正在發送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); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM