2012-12-30 41 views
0

如何將數據發送到下面的PHP文件?我可以建立連接併發送數據,但無法收到響應。我需要發送3個參數,「op」,用戶名和密碼。Android HTTP POST連接到響應文件

switch ($_POST["op"]) { 

    // User Authentication. 
    case 1: 
     $UName = $_POST["UName"]; 
     $UPass = $_POST["UPass"]; 
     $UPass = md5($UPass); 

     //....Some code 

    // New user registration process. 
    case 2: 
     $UName = $_POST["UName"]; 
     $UPass = $_POST["UPass"]; 
     $UEmail = $_POST["UEmail"]; 
     $UNick = $_POST["UNick"]; 
     $UPass = md5($UPass); 

     //....Some code 
     } 

我迄今爲止代碼:

HttpClient httpclient = new DefaultHttpClient(); 
HttpPost httppost = new HttpPost("http://SomeUrl/login.php"); 

     try { 

      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
      nameValuePairs.add(new BasicNameValuePair("1", "dan")); 
      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

      response = httpclient.execute(httppost); 
      String responseBody = EntityUtils.toString(response.getEntity()); 
      Log.d(TAG, ""+responseBody); 

     } catch (ClientProtocolException e) { 
      // TODO Auto-generated catch block 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
     } 

我在做什麼錯?

回答

1

看看你的PHP代碼,至少你需要指定一個op參數。然後根據您要執行的操作,確保指定其他所需的參數。對於用戶認證(OP = 1):

nameValuePairs.add(new BasicNameValuePair("op", "1")); 
nameValuePairs.add(new BasicNameValuePair("UName", "dan")); 
nameValuePairs.add(new BasicNameValuePair("Pass", "somepass")); 

在一個側面說明,你應該使用SSL確保PHP服務,如果您正在使用它來處理敏感的用戶信息。

1

Android的HTTP POST看起來應該是這樣:

 HttpParams httpParams=new BasicHttpParams(); 
    HttpConnectionParams.setConnectionTimeout(httpParams, 10000); 
    HttpConnectionParams.setSoTimeout(httpParams, 10000); 

    // Data to send 
    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 
    nameValuePairs.add(new BasicNameValuePair("UName", "dan")); 
    nameValuePairs.add(new BasicNameValuePair("UPass", "password")); 
    nameValuePairs.add(new BasicNameValuePair("op", "1")); 

    //http post 
    try{ 
    HttpClient httpclient = new DefaultHttpClient(); 
    HttpPost httppost = new HttpPost("http://SomeUrl/login.php"); 
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8")); 
    HttpResponse response = httpclient.execute(httppost); 
    HttpEntity entity = response.getEntity(); 
    is = entity.getContent(); 

    }catch(Exception e){ 

    } 

在你的PHP代碼中,我會強烈建議使用mysql_real_escape_string($ _ POST [ 'UNAME']),否則很容易通過SQL注入攻擊。 我也建議使用SSL連接(HTTPS)或發送密碼只散列(MD5)