2012-04-16 103 views
2

我想连接一个android应用程序到mysql数据库。数据库“tardy_system”运行在由wamp服务器提供的phpmyadmin中。我们在C:/ Wamp/www/Latepass中有一个名为“login.php”的php文件,作为我们的API后端。其主要目标是连接到数据库并运行查询以充当解析的JSON数据。我们在android环境下的java代码被支持连接到index.php代码。我们无法将java代码连接到php api后端。 java代码指定查找文件的http://192.168.0.102:3306/Latepass/login.php。这个lan地址是wamp服务器和数据库的当前内部地址。它目前是动态的,但我们最终会将其更改为静态IP。当我们保存并导出Android apk并运行它后,UPON“Student Login”按钮单击java代码启动,但是Android - 连接到wamp =服务器问候错误

连接总是失败。

这个php代码可以工作,并且可以从局域网上的任何计算机上访问。我们运行了一个测试查询(所有东西都以DEBUGGINGONLY开头),并能够在2个浏览器(Chrome和Firefox)上的局域网中的任何地方读取它。

所以WAMP服务器正在工作 - 因为我们可以通过网络连接到php文件。 PHP文件正在工作 - 因为它确实在浏览器中执行测试查询。

问题: 我认为有些东西阻止了java代码和php代码之间的连接。我们尝试禁用所有防火墙(路由器中的硬件和Windows中的软件).JSON连接使用端口3306.似乎没有任何过滤该端口的东西。

我的PHP代码 - Latepass/login.php中

<?php 
//turn off error reporting 
error_reporting(E_ALL^E_NOTICE^E_WARNING); 

//connect to mySQL 
$connect = mysql_connect("localhost", "root", "") or die(mysql_error("connection error 2")); 

//Select the database 
mysql_select_db("tardy_system")or die("database selection error"); 


//Retrieve the login details via POST 
$username = $_POST['username']; 
$password = $_POST['password']; 

//Query the table android login 
$query = mysql_query("SELECT * FROM students WHERE username='$username' AND password='$password'"); 

//check if there any results returned 
$num = mysql_num_rows($query); 

//If a record was found matching the details entered in the query 
if($num == 1){ 
    //Create a while loop that places the returned data into an array 
    while($list=mysql_fetch_assoc($query)){ 
     //Store the returned data into a variable 
     $output = $list; 

     //encode the returned data in JSON format 
     echo json_encode($output); 

    } 
    //close the connection 
    mysql_close(); 
} 

?> 

StudentloginActivity

package com.android.upgrayeddapps.latepass; 

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.util.ArrayList; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.NameValuePair; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.message.BasicNameValuePair; 
import org.json.JSONObject; 

import android.app.Activity; 
import android.content.Intent; 
import android.content.SharedPreferences; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.Toast; 

public class StudentLoginActivity extends Activity implements OnClickListener{ 
    EditText etUsername; 
    EditText etPassword; 
    Button btnLogin; 

    //Create string variables that will have the input assigned to them 
    String strUsername; 
    String strPassword; 

    //Create a HTTPClient as the form container 
    HttpClient httpclient; 

    //Use HTTP POST method 
    HttpPost httppost; 

    //Create an array list for the input data to be sent 
    ArrayList<NameValuePair> nameValuePairs; 

    //Create a HTTP Response and HTTP Entity 
    HttpResponse response; 
    HttpEntity entity; 


    public void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.studentlogin); 

     initialise(); 
    } 

    private void initialise() 
    { 

     etUsername = (EditText) findViewById(R.id.txtbxStudentUsername); 
     etPassword = (EditText) findViewById(R.id.txtbxStudentLunchID); 
     btnLogin = (Button) findViewById(R.id.btnLoginStudent); 
     //Set onClickListener 
     btnLogin.setOnClickListener(this); 
    } 

    public void onClick(View v) { 

     //Create new default HTTPClient 
     httpclient = new DefaultHttpClient(); 

     //Crate new HTTP POST with URL to php file as parameter 
     httppost = new HttpPost("http://192.168.0.102:3306/Latepass/login.php");   


     //Assign input text to strings 
     strUsername = etUsername.getText().toString(); 
     strPassword = etPassword.getText().toString(); 


     try{ 

      //Create an Array List 
      nameValuePairs = new ArrayList<NameValuePair>(); 

      //place them in an array list 
      nameValuePairs.add(new BasicNameValuePair("username", strUsername)); 
      nameValuePairs.add(new BasicNameValuePair("password", strPassword)); 


      //Add array list to http post 
      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

      //assign executed for container to response 
      response = httpclient.execute(httppost); 

      //check status code, need to check status code 200 
      if(response.getStatusLine().getStatusCode()== 200){ 
        //assign response.getEntity()l 

        //check if entity is not null 
        if(entity !=null){ 
          //create new input stream with received data assigned 
          InputStream instream = entity.getContent(); 

      //Create a JSON Object. Assign converted data as parameter 
      JSONObject jsonResponse = new JSONObject(convertStreamToString(instream)); 

      //Assign JSON responses to local strings 
      String retUser = jsonResponse.getString("username");//mySQL table field 
      String retPass = jsonResponse.getString("password");//mySQL table field 


      //Validate login 
      if(strUsername.equals(retUser)&& strPassword.equals(retPass)){ 

       //Create a new shared preference by getting the preference 
       SharedPreferences sp = getSharedPreferences("logindetails",0); 


       //Edit the shared Preferences 
       SharedPreferences.Editor spedit = sp.edit(); 

       //Put the login details as strings 
       spedit.putString("username", strUsername); 
       spedit.putString("password", strPassword); 

       //Close the editor 
       spedit.commit(); 

       //Display a Toast saying login was a success 
       Toast.makeText(getBaseContext(), "Success!",Toast.LENGTH_SHORT).show(); 


      } else{ 
       //Display a Toast saying it failed 
       Toast.makeText(getBaseContext(), "Invalid Login Details", Toast.LENGTH_SHORT).show(); 
        } 
       } 

      }  

     } catch(Exception e){ 
      e.printStackTrace(); 
      //Display Toast when there is a connection error 
      Toast.makeText(getBaseContext(), "Connection Error Android",Toast.LENGTH_SHORT).show(); 
      Log.e("YourTag", e.getMessage(), e); 
     } 
    }//End try/Catch 


    private static String convertStreamToString(InputStream is) { 
     /* 
     * To convert the InputStream to String we use the BufferedReader.readLine() 
     * method. We iterate until the BufferedReader return null which means 
     * there's no more data to read. Each line will appended to a StringBuilder 
     * and returned as String. 
     */ 
     BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 
     StringBuilder sb = new StringBuilder(); 

     String line = null; 
     try { 
      while ((line = reader.readLine()) != null) { 
       sb.append(line + "\n"); 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      try { 
       is.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
     return sb.toString(); 
    }//End ConvertStreamToString() 

    public void onGotoLatePassActiviy(View View) 
    { 
     Intent intent = new Intent(View.getContext(), LatePassActivity.class); 
     intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
     StudentLoginActivity.this.finish(); 
    } 

} 

问:我失去了在WAMP的配置的东西,不允许我的Java代码来达到PHP码?

目前我得到几个apache errors,这导致我尝试配置它。

今天:在登录过程中,ran wireshark。应用一个tcp源和destination = 3306过滤器。 Got this transmission

+3

试着抓住'Exception'来捕捉它,让它爆炸,看看LogCat实际上说错了什么。不要抓住你的错误! – Blundell 2012-04-16 22:43:26

+0

删除try/catch违反了一些代码的语法。 – UPGRAYEDD 2012-04-17 01:58:36

+2

**将allenComplete类的try/catch替换为'Exception'类,并将其替换为更具体的'IOException'或任何代码抛出。添加“Log.e(”YourTag“,e.getMessage,e);'这样你的异常仍然会显示在控制台中。 – Blundell 2012-04-17 12:11:47

回答

2

WAMP服务器侦听两个端口:端口80和端口3306.端口80用于Web服务器,端口3306用于数据库服务器。

不能通过端口3306连接到您的Web服务器(和PHP)。您将遇到数据库服务器,一旦它意识到客户端正在讲一个不同的协议,就会立即丢弃连接。

比如我的本地机器上:

$ curl http://localhost:3306/ 
5.1.49-1ubuntu8.1+Yt^Y#CeV�]Sd"tIM(|[1"�Got packets out of order$ 

的解决方案是将URL更改为http://192.168.0.102/Latepass/login.php

如果这不工作,确保Web服务器监听:在命令提示符下键入netstat -a -n -p tcp 。你应该看到这样的事情:

Proto Local Address   Foreign Address  State 
TCP 0.0.0.0:80    0.0.0.0:0    LISTENING 
TCP 0.0.0.0:135   0.0.0.0:0    LISTENING 
TCP 0.0.0.0:445   0.0.0.0:0    LISTENING 
... etc... 

如果你没有看到在结束了第一行:80,无论是Apache不听或者你已经改变了口。查看Apache的日志以获取更多详细信息。

+0

Cmd结果与您的结果相同。 – UPGRAYEDD 2012-04-24 23:22:01

+0

我要继续,给你50rep。谢谢你的帮助。我把端口:3306关闭了php文件路径。跑线鲨鱼。 http://i.imgur.com/Lavp2.jpg – UPGRAYEDD 2012-04-25 03:46:30

+0

数据包跟踪显示有效的HTTP请求/响应,您已经超过了您的第一个障碍。如果您需要更多帮助,我建议发布HTTP会话(右键单击数据包 - >按照TCP流) – dwurf 2012-04-25 06:19:48