安卓客户端 - 服务器,用户认证 [英] Android: client-server, user authentication

查看:130
本文介绍了安卓客户端 - 服务器,用户认证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从来没有内置任何这样的Andr​​oid应用程序将与断绝沟通。我想要做的是我要发送的用户名和密码到服务器,与它们匹配的服务器时,用户名和密码匹配下一个屏幕应该显示。接下来的屏幕应该只有一个文本视图说:欢迎用户名。

I have never built any such Android Application which will communicate with the sever. What I want to do is I want to send username and password to the server, match them on server and when the username and password matches next screen should be shown. Next screen should have only one text view saying "Welcome username".

我希望你们告诉我的一步一步的指导作为 -

I want you guys to tell me step by step guide for -

  1. 我应该写在Android应用程序?
  2. 我应该写在服务器端?
  3. 如何以及在哪里写的服务器code?
  4. 在哪种语言,我应该使用服务器端?
  5. 如何保存在服务器上的多个用户名,密码?

我没有真正的服务器。我会在本地主机上运行整个code。

I don't have real server. I will run the entire code on localhost.

更新:

这是我在我的Andr​​oid应用程序写道。我不知道有多少是正确的。

This is what I wrote in my Android app. I don't know how much is correct.

public void clicked(View v) {
    System.out.println("button clicked");
    EditText username = (EditText) findViewById(R.id.edituser);
    EditText password = (EditText) findViewById(R.id.editpass);

    Editable user = username.getText();
    Editable pass = password.getText();

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://192.168.1.101:8080//WebApplication1/sendresponse.java");

    try {
        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("username", user.toString()));
        nameValuePairs.add(new BasicNameValuePair("password", pass.toString()));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);

        Header[] headers = response.getAllHeaders();
        int len = headers.length;
        for(int i=0; i<len; i++) {
            System.out.println("header : " + headers[i]);
        }

        InputStream inputStream = response.getEntity().getContent();

        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);

        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

        StringBuilder stringBuilder = new StringBuilder();

        String bufferedStrChunk = null;

        while((bufferedStrChunk = bufferedReader.readLine()) != null){
            stringBuilder.append(bufferedStrChunk);
        }
        System.out.println("response : " + stringBuilder.toString());

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }



}

我不知道哪种语言将是最适合服务器端。我应该使用REST在服务器端?

I don't know which language will be best for server side. Should I use REST on server side?

推荐答案

我会验证使用PHP。首先,

I'll authenticate using php. First of all,

 HttpPost httppost = new HttpPost("http://10.0.2.2/login.php");

10.0.2.2 reffers从仿真本地主机。对于真正的设备,你需要真正的服务器。

10.0.2.2 reffers localhost from emulator. For real device, you need real server.

您必须创建数据库和放大器;表在本地主机使用phpMyAdmin。(假设你使用WAMP / LAMP)

You have to create DB & table at localhost using phpmyadmin.(Assuming you are using WAMP/LAMP)

现在,我的php文件是这样的:

Now, my php file is like this:

   <?php 
$link=mysql_connect('localhost','root','password');// give your username & password
if (!$link) { 
    die('Could not connect to MySQL: ' . mysql_error()); 
}  
mysql_select_db("database_name"); 
$sql=mysql_query("SELECT * FROM Login_Table_name where user_name = '".$_REQUEST['username']."' and password = '".$_REQUEST['password']."'");
if (mysql_num_rows($sql) > 0) {
 echo "success";
}else{
echo "login failed"; 
}
mysql_close($link); 
?>

(假设你知道在哪里把php文件,对于本地主机)(WWW文件夹WAMP / LAMP)

(Assuming you know where to put the php file, for localhost)(www folder for WAMP/LAMP)

现在,回来的Java,离开步骤高达这一行,因为它是。而变化code从这里到

Now, coming back to java, leave the steps upto this line as it is. And change code from here to

HttpResponse response = httpclient.execute(httppost);
HttpEntity entity=response.getEntity();
String res=EntityUtils.toString(entity);
if(res.contains("success")){
//login success
}
else{
//loginfailed
}

现在你可以说如何存储用户名和密码。是的,就创造一个又一个登记表,包namevaluepairs中并发送到另一个PHP中的SQL查询将变为INSERT INTO。

Now you can say how to store usernames and passwords. Yes, just create an another registration form, wrap namevaluepairs and send to another php in which the sql query will change to 'INSERT INTO'.

注:如果您在本模拟器上使用API​​-14 +,您将获得主线程异常的网络与异常。你必须使用AsynvTask。所以尽量在API-10。

NB: If you run this on emulator with API-14+, you will get an exception- Network on main thread exception. You have to use AsynvTask. so try in API-10.

编辑:

如果你需要一些值从服务器返回,EN code到JSON和发送。变化将是,

If you need some values back from server, encode to JSON and send. changes will be as,

PHP

if(mysql_num_rows($sql)>0){
    while($row=mysql_fetch_assoc($sql)){// you can use either fetch_assoc or fetch_array
    $result[]=$row;
    }
echo json_encode($result);
}

的Java

String res=EntityUtils.toString(entity);
Log.d("TAG","From server:"+res);// to see what server sent
if( ! res.contains("login failed")){
JSONArray jArray = new JSONArray(res); 
if(jArray!=null){
            for(int i=0;i<jArray.length();i++){
                JSONObject jobj = jArray.getJSONObject(i);
                //now, you catch the values using column_name. As,
id=jobj.getInt("_id");name= jobj.getString("Name");
//Note that here _id,Name are column names. Refer server result in logcat for better understanding
            }
}

}

这篇关于安卓客户端 - 服务器,用户认证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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