2

我正在尝试将 android 应用程序连接到 mysql 数据库。数据库“tardy_system”在 wamp 服务器提供的 phpmyadmin 中运行。我们有一个位于 C:/Wamp/www/Latepass 的 php 文件“login.php”作为我们的 API 后端。它的主要目标是连接到数据库并运行查询以用作解析的 JSON 数据。我们在 android 环境中的 java 代码应该连接到 index.php 代码。我们无法将 java 代码连接到 php api 后端。java代码指定查看http://192.168.0.102:3306/Latepass/login.php为文件。这个局域网地址是 wamp 服务器和数据库的当前内部地址。它目前是动态的,但我们最终会将其更改为静态 ip。在我们保存并导出android apk并运行它后,UPON“Student Login”按钮点击java代码启动,但是

连接总是失败。

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

所以 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();  
}

?>

学生登录活动

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 错误,导致我尝试对其进行配置。

今天:在登录过程中运行wireshark。应用了 tcp 源和目标 = 3306 过滤器。得到这个传输

4

1 回答 1

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 的日志。

于 2012-04-23T12:53:07.057 回答