2013-02-14 62 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