2013-10-24 33 views
1

我正在測試一個android到PHP接口和PHP到android回覆系統使用JSON。從Android應用程序它聯繫我的PHP頁面,並創建一個條目到我的數據庫中,但應答從PHP到Android充滿了垃圾。我不知道問題出在哪裏:android json php測試輸出垃圾

//PHP 
<?php 

require_once('functions.php'); 

$json = file_get_contents('php://input'); 
$obj = json_decode($json,true); 



execute("insert into android_test (USERNAME,FULLNAME) values ('".$obj->{'UserName'}."', '".$obj->{'FullName'}."')"); //android_test (ID,IDUSERS,USERNAME,FULLNAME) 
execute("commit"); 

    $posts = array($json); 
    //$posts = array(1); 

    header('Content-type: application/json'); 
    echo json_encode(array('posts'=>$posts)); 


?> 

的Android應用:

public void clickbuttonRecieve(View v) { //send to server 
     try { 
      JSONObject json = new JSONObject(); 
      json.put("UserName", "test2"); 
      json.put("FullName", "1234567"); 


      HttpParams httpParams = new BasicHttpParams(); 
      HttpConnectionParams.setConnectionTimeout(httpParams, 
        TIMEOUT_MILLISEC); 
      HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC); 
      HttpClient client = new DefaultHttpClient(httpParams); 

      String url = "https://www.mypage.com/scripts/androidportalinput.php"; 

      HttpPost request = new HttpPost(url); 
      request.setEntity(new ByteArrayEntity(json.toString().getBytes(
        "UTF8"))); 
      request.setHeader("json", json.toString()); 


      HttpResponse response = client.execute(request); //get feedback 
      HttpEntity entity = response.getEntity(); 
      // If the response does not enclose an entity, there is no need 
      if (entity != null) { 
       InputStream instream = entity.getContent(); 

       String result = RestClient.convertStreamToString(instream); //get feedback 
       Log.i("Read from server", result); 
       Toast.makeText(this, result, 
         Toast.LENGTH_LONG).show(); 
      } 
     } catch (Throwable t) { 
      Toast.makeText(this, "Request failed: " + t.toString(), 
        Toast.LENGTH_LONG).show(); 
     } 
    } 

我接收回來的彈出窗口的「帖子」,但包含的網頁的HTML代碼,以及使JSON編碼數據完整的垃圾發送到我的Android應用程序。

任何解決此問題?

請幫助

回答

0

我可能是錯的,但我看到這是以下可能性。

1)您正在提出錯誤的要求。嘗試在瀏覽器中測試請求,以確保它在那裏正確回覆。

2)您不正確地提供請求。你是否有理由在回覆中包含頭部/腳部。也許一些如何你的網絡服務器添加內容/重定向?

3)數據在路由中被破壞......可能不是......不知道你可以對此做些什麼。

4)您的應用程序正在破壞數據。再次,不太可能..你可以嘗試顯示一次檢索數據,以儘量減少影響數據的可能性。

如果它包含屬於你網站的html,我很確定它的#2。

0

爲什麼不簡單地使用ajax調用從functions.php獲取數據? 如果產生的functions.php JSON字符串你可以去這樣

$阿賈克斯({

網址: '的functions.php',

數據: '你的論點',

數據類型: 'JSON',

成功:函數(GET){

的console.log(get.value);

},

錯誤:功能(E){

的console.log(E)

}

});