通过Java的Andr​​oid的PHP连接 [英] Android PHP connection through Java

查看:150
本文介绍了通过Java的Andr​​oid的PHP连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在android.I初学者已经建立了登录请假module.For通过PHP..I可以与MySQL连接的应用程序试图从网站这个code。

 包com.example.axdroid;
进口的java.util.ArrayList;
进口的java.util.List;进口org.apache.http.Htt presponse;
进口org.apache.http.NameValuePair;
进口org.apache.http.client.HttpClient;
进口org.apache.http.client.ResponseHandler;
进口org.apache.http.client.entity.UrlEn codedFormEntity;
进口org.apache.http.client.methods.HttpPost;
进口org.apache.http.impl.client.BasicResponseHandler;
进口org.apache.http.impl.client.DefaultHttpClient;
进口org.apache.http.message.BasicNameValuePair;进口android.app.Activity;
进口android.app.AlertDialog;
进口android.app.ProgressDialog;
进口android.content.DialogInterface;
进口android.content.Intent;
进口android.os.Bundle;
进口android.view.View;
进口android.view.View.OnClickListener;
进口android.widget.Button;
进口android.widget.EditText;
进口android.widget.TextView;
进口android.widget.Toast;公共类Axdroid延伸活动{
按钮B;
的EditText等,通过;
TextView的电视;
HttpPost httppost;
StringBuffer的缓冲区;
HTT presponse响应;
HttpClient的HttpClient的;
清单<&的NameValuePair GT; namevaluepairs中;
ProgressDialog对话框= NULL;@覆盖
公共无效的onCreate(捆绑savedInstanceState){    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_axdroid);    B =(按钮)findViewById(R.id.Button01);
    等=(EditText上)findViewById(R.id.username);
    通=(EditText上)findViewById(R.id.password);
    电视=(的TextView)findViewById(R.id.tv);    b.setOnClickListener(新OnClickListener(){
        @覆盖
        公共无效的onClick(视图v){            对话框= ProgressDialog.show(Axdroid.this,,
                   验证用户...,真正的);
            意图I =新意图(getApplicationContext(),Userpage.class);
             startActivity(ⅰ);
             新主题(新的Runnable接口(){
                    公共无效的run(){
                        登录();
                    }
                  })。开始();        }
        });}
无效登录(){
    尝试{        HttpClient的=新DefaultHttpClient();
        httppost =新HttpPost(http://192.168.1.222/AndroidLeave/check.php);
        //添加数据
        namevaluepairs中=新的ArrayList<&的NameValuePair GT;(2);
        //始终使用相同的变量名张贴即在Android端变量名和PHP端变量名应该是相似的,
        nameValuePairs.add(新BasicNameValuePair(用户名,et.getText()的toString()修剪())); // $ Edittext_value = $ _ POST ['Edittext_value'];
        nameValuePairs.add(新BasicNameValuePair(密码,pass.getText()的toString()修剪()));
        httppost.setEntity(新UrlEn codedFormEntity(namevaluepairs中));
        //执行HTTP POST请求
        响应= httpclient.execute(httppost);
        //由詹姆斯从$编辑C $ crzheaven ..从这里....
        ResponseHandler所<串GT; ResponseHandler所=新BasicResponseHandler();
        最后弦乐反应= httpclient.execute(httppost,ResponseHandler所);
        的System.out.println(回应:+响应);
        runOnUiThread(新的Runnable(){
            公共无效的run(){
                tv.setText(从PHP回应:+响应);
                dialog.dismiss();
            }
        });        如果(response.equalsIgnoreCase(用户找到)){
            runOnUiThread(新的Runnable(){
                公共无效的run(){
                    Toast.makeText(Axdroid.this,登录成功,Toast.LENGTH_SHORT).show();
                }
            });            startActivity(新意图(getApplicationContext(),Userpage.class));
        }其他{
            showAlert();
        }    }赶上(例外五){
        dialog.dismiss();
        的System.out.println(异常:+ e.getMessage());
    }
}
公共无效showAlert(){
    Axdroid.this.runOnUiThread(新的Runnable(){
        公共无效的run(){
            AlertDialog.Builder建设者=新AlertDialog.Builder(Axdroid.this);
            builder.setTitle(登录错误。);
            builder.setMessage(用户未找到。)
                   .setCancelable(假)
                   .setPositiveButton(OK,新DialogInterface.OnClickListener(){
                       公共无效的onClick(DialogInterface对话,诠释的id){
                       }
                   });
            AlertDialog警报= builder.create();
            alert.show();
        }
    });
}}

我无法为在调试code ...控制从HttpClient的跳跃赶code.Would AP preciate任何帮助分拣这使这项工作。

这是PHP file.I已分别检查,它是工作。

 < PHP
$ hostname_localhost =localhost的;
$ database_localhost =MyDatabase的;
$ username_localhost =根;
$ password_localhost =;
$本地主机= mysql_connect($ hostname_localhost,$ username_localhost,$ password_localhost)
要么
trigger_error(mysql_error(),E_USER_ERROR);mysql_select_db($ database_localhost,$本地主机);
$用户名= $ _ POST [用户名];
$密码= $ _ POST ['密码'];
$ query_search ='$用户名和密码='。$的密码,从tbl_user其中username =选择*'。 ';
$ query_exec =的mysql_query($ query_search)或死亡(mysql_error());
$行= mysql_num_rows($ query_exec);
//回声$行;
如果($行== 0){
回声没有找到这样的用户;
}
其他{
回声用户找到;
}
?>

@ashwani
这是present Axdroid.java页面(主要活动页)

 公共类Axdroid延伸活动{
按钮B;
的EditText等,通过;
TextView的电视;
HttpPost httppost;
StringBuffer的缓冲区;
HTT presponse响应;
HttpClient的HttpClient的;
清单<&的NameValuePair GT; namevaluepairs中;
ProgressDialog对话框= NULL;@覆盖
公共无效的onCreate(捆绑savedInstanceState){    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_axdroid);    B =(按钮)findViewById(R.id.Button01);
    等=(EditText上)findViewById(R.id.username);
    通=(EditText上)findViewById(R.id.password);
    电视=(的TextView)findViewById(R.id.tv);    b.setOnClickListener(新OnClickListener(){
        @覆盖
        公共无效的onClick(视图v){            字符串URL =htt​​p://192.168.1.222/AndroidLeave/check.php;
            JSONParser jparser =新JSONParser();
            ArrayList的<&的NameValuePair GT; PARAMS =新的ArrayList<&的NameValuePair GT;();
            params.add(新BasicNameValuePair(标签,的getCategory));
            params.add(新BasicNameValuePair(用户名,et.getText()的toString()));
            params.add(新BasicNameValuePair(密码,pass.getText()的toString()));
            JSONObject的jObj = jparser.makeHtt prequest(URL,POST,则params);尝试{
                字符串成功= jObj.get(成功)的toString()。
            }赶上(JSONException E){
                // TODO自动生成catch块
                e.printStackTrace();
            }
        }
        });}'


解决方案

解析我用下面的类中的数据

JsonParser.java

 公共类JSONParser {    InputStream为= NULL;
    JSONObject的jObj = NULL;
    JSON字符串=;    公共JSONParser(){
    }    //函数得到JSON的网址
    //通过HTTP POST或GET方法
    公众的JSONObject makeHtt prequest(URL字符串,字符串的方法,
            清单<&的NameValuePair GT; PARAMS){        //使HTTP请求
        尝试{            //检查请求的方法
            如果(方法==POST){
                //请求方法是POST
                // defaultHttpClient
                DefaultHttpClient的HttpClient =新DefaultHttpClient();
                HttpPost httpPost =新HttpPost(URL);
                httpPost.setEntity(新UrlEn codedFormEntity(PARAMS));                HTT presponse HTT presponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = HTT presponse.getEntity();
                是= httpEntity.getContent();            }否则如果(方法==GET){
                //请求方法是GET
                DefaultHttpClient的HttpClient =新DefaultHttpClient();
                字符串中的paramString = URLEn codedUtils.format(参数,可以UTF-8);
                网址+ =? +中的paramString;
                HTTPGET HTTPGET =新HTTPGET(URL);                HTT presponse HTT presponse = httpClient.execute(HTTPGET);
                HttpEntity httpEntity = HTT presponse.getEntity();
                是= httpEntity.getContent();
            }        }赶上(UnsupportedEncodingException五){
            e.printStackTrace();
        }赶上(ClientProtocolException E){
            e.printStackTrace();
        }赶上(IOException异常五){
            e.printStackTrace();
        }
        尝试{
            读者的BufferedReader =新的BufferedReader(新的InputStreamReader(
                    是,UTF-8),8);
            StringBuilder的SB =新的StringBuilder();            Log.d(在JSON解析器读取器的值,reader.toString());
            串线=;
            而((行= reader.readLine())!= NULL){
                Log.d(在JsonParser线,线);
                sb.append(行+\\ n);
            }
            is.close();
            JSON = sb.toString();
            Log.d(Json的价值,JSON);        }赶上(例外五){
            Log.d(缓冲区错误,错误转换结果+ e.toString());
        }        //尝试分析字符串到一个JSON对象
        尝试{            jObj =新的JSONObject(JSON);
            JSON =;
        }赶上(JSONException E){
            Log.d(JSON解析器,错误分析数据+ e.toString());
        }
        返回jObj;
    }
}

现在您的活动试图通过一个URL像这样

 字符串的URL =这里把你的网址
JSONParser jparser =新JSONParser();
PARAMS =新的ArrayList<&的NameValuePair GT;();
params.add(新BasicNameValuePair(标签,的getCategory));
params.add(新BasicNameValuePair(用户名,username.getText()的toString()));
params.add(新BasicNameValuePair(密码,password.getText()的toString()));
JSONObject的jobj = jparser.makeHtt prequest(URL,POST,则params);

//现在这里从JSON检索数据:

 字符串成功= jobj.get(成功);

希望这有助于!

也是你的PHP文件之前已使用 json_en code 函数echo

I am a beginner in android.I have built an application for login for leave module.For connecting it with mySql through PHP..I tried this code from a website.

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

}

I am unable to make this work as while debugging the code...the control jumps from httpclient to catch code.Would appreciate any help in sorting this.

This is the PHP file.I have checked it seperately and it is working.

<?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 This is the present Axdroid.java page(main activity page)

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


        }
        });}'

解决方案

for parsing the data I use the following class

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

now in your activity try to pass a url like this

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

//now here retrieve the data from json as:

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

Hope this helps!

also in your php file you have to use the json_encode function before echo !

这篇关于通过Java的Andr​​oid的PHP连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆