2013-02-14 87 views
0

我試過看過幾個鏈接,但我似乎無法弄清楚。我想從我的Android應用程序發送包含'用戶名'和'密碼'的JSON對象。但我不確定這些數據是否真的被髮送到網絡服務。我不太確定,如果我有正確的代碼來閱讀php腳本中的JSON對象。從Android接收JSON對象到PHP Webservice

JSONObject jsonObject = new JSONObject(); 

    String userID = ""; 

    HttpClient httpClient = new DefaultHttpClient(); 
    HttpPost httpPost = new HttpPost(loginURI); 
    HttpParams httpParams = new BasicHttpParams(); 
    HttpConnectionParams.setConnectionTimeout(httpParams, 10000); 
    HttpConnectionParams.setSoTimeout(httpParams,10000); 

    try { 

     jsonObject.put("username", username); 
     jsonObject.put("password", password); 

     JSONArray array = new JSONArray(); 

     StringEntity stringEntity = new StringEntity(jsonObject.toString()); 
     stringEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); 
     httpPost.setEntity(stringEntity); 
     HttpResponse httpResponse = httpClient.execute(httpPost); 

     HttpEntity entity = httpResponse.getEntity(); 

     if (entity != null) { 
      userID = EntityUtils.toString(httpResponse.getEntity()); 
      Log.i("Read from server", userID); 
     } 

    }catch (IOException e){ 
     Log.e("Login_Issue", e.toString()); 
    }catch (JSONException e) { 
     e.printStackTrace(); 
    } 

這是PHP腳本的開始。

<?php 

include('dbconnect.php'); 

$tablename = 'users'; 

//username and password sent from android 
$username=$_REQUEST['username']; 
$password=$_REQUEST['password']; 

..... 
?> 

你能告訴我我在做什麼錯嗎?我似乎無法弄清楚。

謝謝

回答

1

你應該的NameValuePairs列表添加到您的HttpPost對象,所以你知道你可以使用你的PHP腳本來檢索數據的密鑰。請參閱下面的示例代碼片段。

Java的:

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
nameValuePairs.add(new BasicNameValuePair("username", username)); 
nameValuePairs.add(new BasicNameValuePair("password", password)); 
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

的PHP:

$username = $_POST['username'] 
$password = $_POST['password'] 
+0

感謝。它做了詭計。你能告訴我$ _REQUEST和$ _POST之間的區別嗎?謝謝 – mokko211 2013-02-14 23:32:35

+2

$ _REQUEST適用於所有類型的方法,包括get和post。 $ _POST僅用於發佈方法 – 2013-02-15 00:56:54