php rest API POST请求返回null

时间:2017-07-20 16:31:21

标签: php rest return-value

我已在this tutorial创建了REST API库 - 请注意我是phpREST中的新手...

现在,我在调用POST请求时遇到困难。主要的返回功能如下:

// Requests from the same server don't have a HTTP_ORIGIN header
if (!array_key_exists('HTTP_ORIGIN', $_SERVER)) {
    $_SERVER['HTTP_ORIGIN'] = $_SERVER['SERVER_NAME'];
}

try {
    $API = new MyAPI($_REQUEST['request'], $_SERVER['HTTP_ORIGIN']);
    $res = $API->processAPI();
    echo $res;   // contains my json as expected
    return $res; // always empty string
} catch (Exception $e) {
    echo "Exception: " . json_encode(Array('error' => $e->getMessage()));
}

修改 我在API调用方法中尝试了更简单的方法,即:

try {
    $res = json_encode(Array('test' => "my message"));
    // comment out one or the other to check output...
    //echo $res;
    return $res;
} catch (Exception $e) {
    echo "Exception: " . json_encode(Array('error' => $e->getMessage()));
}

echo的结果是(我得到responese的方式在下面......#字符之间的确切响应):

#{"test":"my message"}#

return的结果是

##

编辑2 以下是我从C#调用API的方法:

using (HttpClient client = new HttpClient()) { 
    JObject jo = new JObject();
    jo.Add("usr", "username");
    jo.Add("pwd", "password");
    Uri url = new Uri(string.Format("{0}/{1}", RestUrl, "login"));
    StringContent content = new StringContent(jo.ToString(), Encoding.UTF8, "application/json");
    HttpResponseMessage response = await client.PostAsync(url, content);
    bool isOk = response.StatusCode == System.Net.HttpStatusCode.OK;
    // this is where I get the result from...
    var res = response.Content.ReadAsStringAsync().Result;
}

我真的不明白这一点 - 有人可以用非PHP专家的术语解释吗?

0 个答案:

没有答案