Android POST JSON与服务器的不一致

时间:2014-01-28 02:38:56

标签: php android json

我的代码将json对象发布到服务器。这是我的PHP

<?php
$jsonString = file_get_contents('php://input');
$jsonObj = json_decode($jsonString, true);

if( !empty($jsonObj)) { 
        $players = $jsonObj['Players'];
        $details = $jsonObj['Details'];
        $events  = $jsonObj['Events'];
        print "YES";
        var_dump($players);
}else{
print "NO";
}
 ?> 

这是android代码的片段。

inputStream = httpResponse.getEntity().getContent();

        String status = httpResponse.getStatusLine().toString();
        if (!status.equals("HTTP/1.1 500 Internal Server Error")){
            if(inputStream != null){
                result = convertInputStreamToString(inputStream);   
            }
            else{
                result = "Did not work!";
            }
        }else{
            System.out.println("500 Error");

        }



    } catch (Exception e) {
        Log.d("InputStream", e.getLocalizedMessage());
        System.out.println(e);
    }

    System.out.println(result);
    return result;

我遇到的问题是,当我运行此代码时,在PHP页面上输出“NO”,但我从服务器(结果)得到的响应显示“是”并输出JSON。

  • 任何人都可以解释一下吗? enter image description here

enter image description here

1 个答案:

答案 0 :(得分:1)

我在评论中回答,但是@Tanis.7x说我应该添加答案。

$jsonObj是空的,你得到的不是&#39;当你通过浏览器运行代码时(你没有通过任何json)。看来你通过android请求传递了一些json。

如果要在浏览器中显示json数据,则需要在服务器上保留json数据。

$jsonString = file_get_contents('php://input');
$jsonObj = json_decode($jsonString, true);

$file = 'tmp';

if(!empty($jsonObj)) { 
    file_put_contents($file, $jsonString);
} else {
    $content = file_get_contents($file);
    if ($content) {
        echo $content;
        //$jsonObj = json_decode($content, true);
    } else {
        echo 'NO';
    }
}