2014-01-28 38 views
0

我的代碼發佈一個json對象到服務器。這是我的PHPAndroid POST JSON到服務器不一致

<?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; 

我遇到的問題是,當運行此代碼「NO」是PHP頁面上輸出,但我從服務器(結果)獲得響應表示「是」,並輸出JSON。

  • 任何人都可以解釋這一點嗎? enter image description here

enter image description here

+0

$ jsonObj是空的,當你通過瀏覽器運行代碼(你不通過任何json)時你會得到'NO'。看來你通過android請求傳遞一些json。有什麼問題? – rNix

+0

是的,所以當我通過android和刷新頁面的數據傳遞給服務器(點擊按鈕)應該在瀏覽器中的輸出不是YES? –

+0

你可以顯示如何傳遞數據從android到服務器的片段? – edisonthk

回答

1

我的評論回答,但@ Tanis.7x說我要補充一個答案。

$jsonObj爲空,當您通過瀏覽器運行代碼(您不通過任何json)時,您會得到'NO'。看來你通過android請求傳遞一些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'; 
    } 
}