php - 通过 Java 连接 Android PHP

标签 php android mysql

我是 android 的初学者。我已经为休假模块构建了一个登录应用程序。为了通过 PHP 将它与 mySql 连接。我从网站上尝试了这段代码。

package com.example.axdroid;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class Axdroid extends Activity {
Button b;
EditText et,pass;
TextView tv;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_axdroid);

    b = (Button)findViewById(R.id.Button01); 
    et = (EditText)findViewById(R.id.username);
    pass= (EditText)findViewById(R.id.password);
    tv = (TextView)findViewById(R.id.tv);

    b.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

            dialog = ProgressDialog.show(Axdroid.this, "",
                   "Validating user...", true);
            Intent i=new Intent(getApplicationContext(),Userpage.class);
             startActivity(i);                
             new Thread(new Runnable() {
                    public void run() {
                        login();                         
                    }
                  }).start();         

        }
        });}
void login(){
    try{           

        httpclient=new DefaultHttpClient();
        httppost= new HttpPost("http://192.168.1.222/AndroidLeave/check.php");
        //add your data
        nameValuePairs = new ArrayList<NameValuePair>(2);
        // Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar,
        nameValuePairs.add(new BasicNameValuePair("username",et.getText().toString().trim()));  // $Edittext_value = $_POST['Edittext_value'];
        nameValuePairs.add(new BasicNameValuePair("password",pass.getText().toString().trim()));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        //Execute HTTP Post Request
        response=httpclient.execute(httppost);
        // edited by James from coderzheaven.. from here....
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        final String response = httpclient.execute(httppost, responseHandler);
        System.out.println("Response : " + response);
        runOnUiThread(new Runnable() {
            public void run() {
                tv.setText("Response from PHP : " + response);
                dialog.dismiss();
            }
        });

        if(response.equalsIgnoreCase("User Found")){
            runOnUiThread(new Runnable() {
                public void run() {
                    Toast.makeText(Axdroid.this,"Login Success", Toast.LENGTH_SHORT).show();
                }
            });

            startActivity(new Intent(getApplicationContext(), Userpage.class));
        }else{
            showAlert();               
        }

    }catch(Exception e){
        dialog.dismiss();
        System.out.println("Exception : " + e.getMessage());
    }
}
public void showAlert(){
    Axdroid.this.runOnUiThread(new Runnable() {
        public void run() {
            AlertDialog.Builder builder = new AlertDialog.Builder(Axdroid.this);
            builder.setTitle("Login Error.");
            builder.setMessage("User not Found.") 
                   .setCancelable(false)
                   .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                       public void onClick(DialogInterface dialog, int id) {
                       }
                   });                    
            AlertDialog alert = builder.create();
            alert.show();              
        }
    });
}

}

我无法在调试代码时使它正常工作...控件从 httpclient 跳转到捕获代码。如果能帮助解决这个问题,我们将不胜感激。

这是 PHP 文件。我已经单独检查过它,它可以正常工作。

<?php
$hostname_localhost ="localhost";
$database_localhost ="mydatabase";
$username_localhost ="root";
$password_localhost ="";
$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
or
trigger_error(mysql_error(),E_USER_ERROR);

mysql_select_db($database_localhost, $localhost);


$username = $_POST['username'];
$password = $_POST['password'];


$query_search = "select * from tbl_user where username = '".$username."' AND password = '".$password. "'";
$query_exec = mysql_query($query_search) or die(mysql_error());
$rows = mysql_num_rows($query_exec);
//echo $rows;
if($rows == 0) {
echo "No Such User Found";
}
else  {
echo "User Found";
}
?>

@ashwani 这是当前的Axdroid.java页面( Activity 主页面)

public class Axdroid extends Activity {
Button b;
EditText et,pass;
TextView tv;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_axdroid);

    b = (Button)findViewById(R.id.Button01); 
    et = (EditText)findViewById(R.id.username);
    pass= (EditText)findViewById(R.id.password);
    tv = (TextView)findViewById(R.id.tv);

    b.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

            String url="http://192.168.1.222/AndroidLeave/check.php";
            JSONParser jparser= new JSONParser();
            ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("tag", "getcategory"));
            params.add(new BasicNameValuePair("username", et.getText().toString()));
            params.add(new BasicNameValuePair("password", pass.getText().toString()));
            JSONObject jObj= jparser.makeHttpRequest(url, "POST", params);try {
                String success = jObj.get("success").toString();
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }               


        }
        });}'

最佳答案

我使用下面的类来解析数据

JsonParser.java

public class JSONParser {

    InputStream is = null;
    JSONObject jObj = null;
    String json = "";

    public JSONParser() {
    }

    // function get json from url
    // by making HTTP POST or GET method
    public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params) {

        // Making HTTP request
        try {

            // check for request method
            if (method == "POST") {
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            } else if (method == "GET") {
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "UTF-8"), 8);
            StringBuilder sb = new StringBuilder("");

            Log.d("reader value in json parser", reader.toString());
            String line = "";
            while ((line = reader.readLine()) != null) {
                Log.d("line in JsonParser", line);
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
            Log.d("Json value", json);

        } catch (Exception e) {
            Log.d("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {

            jObj = new JSONObject(json);
            json = "";
        } catch (JSONException e) {
            Log.d("JSON Parser", "Error parsing data " + e.toString());
        }
        return jObj;
    }
}

现在在你的 Activity 中尝试传递这样的 url

String url="place your url here";
JSONParser jparser= new JSONParser();
params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", "getcategory"));
params.add(new BasicNameValuePair("username", username.getText().toString()));
params.add(new BasicNameValuePair("password", password.getText().toString()));
JSONObject jobj= jparser.makeHttpRequest(url, "POST", params); 

//现在从 json 中检索数据为:

String success= jobj.get("success");

希望这对您有所帮助!

同样在您的 php 文件中,您必须在 echo 之前使用 json_encode 函数!

关于php - 通过 Java 连接 Android PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12947772/

相关文章:

Mysql 乘法运算

php - 查询 Google map 某个位置的周边城市

php - 如何根据相关OneToMany关联中的条件选择一组实体?

android - 如何解决此 adb 授予权限错误

mysql - 从数据库表中删除冗余行

mysql - MySQL在mpdf中每行创建一个新的页面宽度

javascript - 是否可以为提供 JS 内容的 PHP 文件指定缓存验证器?

php - 如何编辑 Woocommerce Single Product Meta 模板中显示的内容?

java - 如何在 Android/Java 的 for 循环中等待迭代之间的特定时间?

android - 通用打印机驱动程序 - Android