2011-11-22 216 views
3

嗨!我正在開發基於互聯網的應用程序在Android中。我想要做的是發送一個用戶名和密碼到一個PHP的Web服務器,並返回從服務器的響應。響應可以是文本,如「有效」或「無效」,如果響應是「有效」,則應啓動新的活動。我不知道如何從android發送數據到PHP服務器,並從服務器讀取響應。以下PHP代碼將生成正確的響應。請幫助我,因爲這對我計算機科學專業的最後一年項目很重要。謝謝!用android連接到PHP web服務器

<?php 
$user= $_POST["uid"]; 
$pwd=$_POST["pass"]; 
$con= mysql_connect("localhost","root"); 
if(!$con) 
{ 
    die("Not able to connect"); 

} 
mysql_select_db("try",$con); 
$result=mysql_query("Select * from info where uid='$user'and pass='$pwd'"); 

if(mysql_num_rows($result)<=0) 
{ 
    echo "unsuccessful"; 
} 
else 
{ 
    echo "successful"; 
} 
mysql_close($con); 
?> 
+1

你應該問你的導師對SQL注入和你的數據庫需要一個PW爲root用戶價值....的 –

+0

可能重複[如何在Android中執行HTTP GET? ](http://stackoverflow.com/questions/1162260/how-do-perform-http-get-in-android) – zaf

+0

爲什麼你發佈相同的問題,以其他方式。你只是混淆了人。 – Pawan

回答

1

嘗試使用這樣的:

<? 
$sock = fsockopen("url.com", 80, $errno, $errstr, 30); 
if ($sock) 
{ 
fwrite($sock, "GET /some_request HTTP/1.0\r\n" . 
      "Host: url.com\r\n" . 
      "\r\n"); 

$beg = 0; 
while (!feof($sock)) 
    echo fread($sock, 128); 

fclose($sock); 
} 
?> 
+0

其實我的PHP代碼是好的,但我想知道的是,我怎麼能發送請求從Android到PHP併發送回顯消息回到Android –

+0

嗯......我不明白你的問題。看看這裏:http://stackoverflow.com/questions/3505930/make-in-http-request-with-android – Angrybambr

1

從您的應用程序,做這樣的事情:

URL url = new URL("http://www.your-site.com/auth_user.php?username="+username+"&pwd="+pwd);   
    URLConnection authUserConn = url.openConnection(); 
    BufferedReader in = new BufferedReader(new InputStreamReader(authUserConn.getInputStream())); 
    String inputLine; 
    String res = ""; 
    if ((inputLine = in.readLine()) != null) 
     res += inputLine; 
    in.close(); 
    //parse result 
    Integer success = Integer.valueOf(res); 
    // ... 
1

要發送UIDPass到PHP文件::

List<NameValuePair> updatemsg = new ArrayList<NameValuePair>(); 
updatemsg.add(new BasicNameValuePair("uid", uidmsg)); 
updatemsg.add(new BasicNameValuePair("pass", passmsg)); 
ttpClient httpclient = new DefaultHttpClient(); 
HttpConnectionParams.setConnectionTimeout(httpclient.getParams(), 10000); //Timeout Limit 
HttpPost httppost = new HttpPost("your_url.php"); 
httppost.setEntity(new UrlEncodedFormEntity(updatemsg)); 
httpclient.execute(httppost); 

而擺脫PHP文件::

  HttpClient httpclient = new DefaultHttpClient(); 
      HttpConnectionParams.setConnectionTimeout(httpclient.getParams(), 10000); //Timeout Limit 
      HttpPost httppost = new HttpPost("your_url.php"); 
      httppost.setEntity(new UrlEncodedFormEntity(updatemsg)); 
      HttpResponse response = httpclient.execute(httppost); 

      InputStream content = response.getEntity().getContent(); 
      BufferedReader buffer = new BufferedReader(new InputStreamReader(content)); 
      String s = ""; 
      while ((s = buffer.readLine()) != null) { 

       //s is the returned value; 

      }