2012-04-16 5 views
2

アンドロイドアプリケーションをmysqlデータベースに接続しようとしています。データベース "tardy_system"は、wamp serverによって提供されるphpmyadminの中で実行されています。 APIのバックエンドとして機能するC:/ Wamp/www/Latepassにある "login.php"というファイルがあります。その主な目的は、データベースに接続し、解析されたJSONデータとして機能するクエリを実行することです。アンドロイド環境内のJavaコードは、index.phpコードに接続するためにサポートされています。 Javaコードをphp apiバックエンドに接続できません。 Javaコードでは、http://192.168.0.102:3306/Latepass/login.phpのファイルを検索するように指定されています。このLANアドレスは、ワンプサーバーとデータベースの現在の内部アドレスです。現時点では動的ですが、最終的に静的IPに変更されます。保存してアンドロイドAPKをエクスポートして実行した後、UPON "Student Login"ボタンをクリックするとJavaコードが起動します。Android - wampへの接続=サーバーの挨拶エラー

接続は常に失敗します。

PHPコードは動作し、LAN上のどのコンピュータからでもアクセス可能です。テストクエリ(すべては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(); 
} 

?> 

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

} 

質問:私は私のJavaコードは、PHPに到達することはできませんWAMPの構成で何かが足りませんコード?

現在、私はそれを設定しようとするいくつかのapache errorsを取得しています。

今日:ログインプロセス中に迷惑メールが鳴ります。 TCPソースと宛先= 3306フィルタが適用されました。 Got this transmission

+3

「Exception」をキャッチして、それを爆発させて、LogCatが実際に言ったことを見てみましょう。あなたのエラーを隠すことはありません! – Blundell

+0

try/catchを削除すると、コードの構文に違反します。 – UPGRAYEDD

+2

**すべての例外のExceptクラスのtry/catchを置き換え、より具体的な 'IOException'またはコードがスローするものに置き換えます。あなたのトーストの代わりに(または同様に)行を追加します。 'Log.e(" YourTag "、e.getMessage、e);'そのようにしても例外はコンソールに表示されます。 – Blundell

答えて

2

WAMPサーバーは、ポート80とポート3306の2つのポートで待機します。ポート80はWebサーバー用、ポート3306はデータベースサーバー用です。

は、ポート3306でWebサーバー(およびPHP)に接続できません。クライアントが別のプロトコルを使用していることを認識すると、すぐに接続を切断します。私のローカルマシン上

例:コマンドプロンプトnetstat -a -n -p tcpに:

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

ソリューションは、Webサーバがリッスンしていることを確認、これが機能しない場合http://192.168.0.102/Latepass/login.php

にURLを変更することです。

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

結果はあなたのものと同じです。 – UPGRAYEDD

+0

私は先に進み、50repを与えます。ご協力いただきありがとうございます。私はポートを取った:PHPファイルパスから3306。ワイヤーサメを走らせた。 http://i.imgur.com/Lavp2.jpg – UPGRAYEDD

+0

そのパケットトレースは有効なHTTPリクエスト/レスポンスを示しています。あなたは最初のハードルを過ぎています。もっと助けが必要な場合は、HTTPの会話を投稿することをお勧めします(パケットを右クリック - > TCPストリームに従う) – dwurf

関連する問題