Rest Web API返回null响应

时间:2014-03-21 20:28:18

标签: php json

我是Web服务的新手,所以我希望我能正确解释一下。

我正在编写RESTful Web API但我的应用程序正在获得空响应。我的代码片段:

function sendResponse($status = 200, $body = '', $content_type = 'application/json')
{
    $status_header = 'HTTP/1.1 ' . $status . ' ' . getStatusCodeMessage($status);
    header($status_header);
    header('Content-type: ' . $content_type);
    echo $body;
}

function find_events()
{
  global $user_name, $password, $database, $serverip;

  $db_handle = mysql_connect($serverip, $user_name, $password);
  $db_found = mysql_select_db($database, $db_handle);
  if ($db_found) {;
        $result = array();
        $SQL = "SELECT * FROM Event_Record";
        $sqlresult = mysql_query($SQL);
        while ( $db_field = mysql_fetch_assoc($sqlresult) ) {
            $arr = array_map('utf8_encode', $db_field);
            $result[] = $arr;
        }
    } else {
        $result = "error";
    }
    mysql_close($db_handle);

  sendResponse(200, json_encode($result));
}

根据我见过的其他答案,我添加了' utf8_encode'如果是问题...

当我用浏览器测试时,我得到以下内容,告诉我json_encode的结果不是null:

[{"eventGUID":"1","latitude":"-71.466","longitude":"42.7624","type":"1","title":"United Way Event","address":"100 Main Street, Nashua MH","start":"0000-00-00 00:00:00","end":"0000-00-00 00:00:00","description":"We appreciae your hard work","create":"0000-00-00 00:00:00","expire":"0000-00-00 00:00:00","owner":"1"},{"eventGUID":"2","latitude":"-71.4648","longitude":"42.7624","type":"2","title":"New Event","address":"Nashua, NH","start":"0000-00-00 00:00:00","end":"2001-00-00 00:00:00","description":"Event","create":"2002-00-00 00:00:00","expire":"2002-00-00 00:00:00","owner":"1"}]

我添加了一个测试程序:

function do_test()
{
    $test_result = array();
    $test_result[] = "TEST:'1',RESPONSE:'AOK'";
    $test_result[] = "TEST:'2',RESPONSE:'GOOD'";

  sendResponse(200, json_encode($test_result));
}

我的应用确实从测试中得到了正确的答案。这似乎表明协议和标题都很好。

知道我做错了吗?

3 个答案:

答案 0 :(得分:0)

部分中的

:sendResponse(200,json_encode($ value));

我看不到你在哪里设置$ value的值。我认为你的意思是$ result

sendResponse(200,json_encode($ result));

答案 1 :(得分:0)

我首先使用错误语句在if语句之外启动$ result。如果您的db调用失败,则需要发送401或其他一些HTTP错误代码。此外,您可能需要强制缓冲区输出回声。 要回答一个你没有提出的问题,你应该使用一个框架(甚至是一个微框架)发送API响应,因为它可以节省你很多时间,让你的用户更快乐。

答案 2 :(得分:0)

好的,我回答了自己的问题。

当我评论最后一个答案时,我决定尝试一下。我将eventGUID更改为数据库中的event_guid,它神奇地工作了。虽然它有效但我仍然感到困惑,因为我知道JSON中允许使用大写字母,并且阻止结果的是发送响应的Web服务和我的应用程序获得响应之间的结果。

感谢您的帮助!!

相关问题