鱼C论坛

 找回密码
 立即注册
查看: 11660|回复: 4

android学习之访问互联网--服务端的登录验证

[复制链接]
发表于 2014-11-7 21:06:24 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
实现原理概述:
   通过客户端输入用户名和密码,然后提交到服务端进行验证的过程!因为考虑到是联系,数据较小,所以服务端的用户名与密码就存到list集合里面了!
首先,需要配置服务端的代码!这里是有sevlet来实现的:

  1. package cn.cxrh.daomain;

  2. import java.io.IOException;
  3. import java.util.*;
  4. import javax.servlet.ServletException;
  5. import javax.servlet.http.HttpServlet;
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;

  8. import org.omg.CORBA.Request;

  9. import cn.cxrh.daomain.*;

  10. import com.sun.xml.internal.bind.v2.schemagen.xmlschema.List;

  11. public class UserSer extends HttpServlet {

  12.         @Override
  13.         protected void doGet(HttpServletRequest req, HttpServletResponse resp)
  14.                         throws ServletException, IOException {
  15.                 // TODO Auto-generated method stub
  16.                 boolean flag = false;
  17.                 ArrayList<User> users =  new ArrayList<User>();
  18.                 users.add(new User("xiaobaima","123","2014-11-07 17:14:45"));
  19.                 users.add(new User("xiaojiayu","345","2014-11-07 17:18:34"));
  20.                
  21.                 String username = new String(req.getParameter("username"));
  22.                 String password = req.getParameter("password");
  23.                
  24.                 System.out.println("username=" + username);
  25.                 System.out.println("password=" + password);
  26.                 if(username != null && !"".equals(username) && password != null && !"".equals(password))
  27.                 {
  28.                         for(User user : users)
  29.                         {
  30.                                 if(username.equals(user.getUsername()) && password.equals(user.getPassword()))   如果用户名与密码匹配的话
  31.                                 {
  32.                                         resp.getOutputStream().write("登录成功!".getBytes());  //就给送这个数据给客户端
  33.                                        
  34.                                         flag = true;
  35.                                         break;
  36.                                 }
  37.                         }
  38.                        
  39.                         if(!flag)
  40.                         {
  41.                                 resp.getOutputStream().write("登录失败!".getBytes());
  42.                         }
  43.                 }
  44.         }

  45.         @Override
  46.         protected void doPost(HttpServletRequest req, HttpServletResponse resp)
  47.                         throws ServletException, IOException {
  48.                 // TODO Auto-generated method stub
  49.                 this.doGet(req, resp);
  50.         }
  51. }

复制代码
然后在客户单这边的话,就需要与服务端产生链接与交互:
首先是访问互联网的权限:
  1. <uses-permission android:name="android.permission.INTERNET"/
复制代码

然后在java代码里面写交互的代码:
  1. public static byte[] loadDate(InputStream is) throws Exception
  2.         {    <font color="#2e8b57">//将服务端像客户端发来的输入流里面的数据转化为字节数组的形式</font>
  3.                 ByteArrayOutputStream bos = new ByteArrayOutputStream();
  4.                 byte[] buffer = new byte[1024];
  5.                 int len = -1;
  6.                
  7.                 while((len = is.read(buffer)) != -1)
  8.                 {
  9.                         bos.write(buffer,0,len);
  10.                 }
  11.                 is.close();
  12.                 bos.close();
  13.                 return bos.toByteArray();
  14.         }
复制代码

首先要说明的是一般的写法有两种:
1.用HttpURLConnection实现:
其关键代码如下:
GET请求:
  1. String path = "http://192.168.0.115:8080/qqServer/loginServlet?username=" +
  2.                                         URLEncoder.encode(username,"utf-8") + "&password="+URLEncoder.encode(password,"utf-8");
  3.                         URL url = new URL(path);
  4.                         HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  5.                         conn.setRequestMethod("GET");
  6.                         conn.setConnectTimeout(5000);
  7.                        
  8.                         int code = conn.getResponseCode();
  9.                        
  10.                         if(code == 200)
  11.                         {
  12.                                 InputStream is = conn.getInputStream();
  13.                                 return new String(loadDate(is),"GBK");
  14.                                
  15.                         }
复制代码
POST请求:

  1. String path="http://192.168.0.115:8080/qqServer/loginServlet";
  2.                         String data = "username=" + URLEncoder.encode(username,"utf-8") +
  3.                                         "&password=" + URLEncoder.encode(password,"utf-8");
  4.                         URL url = new URL(path);
  5.                         HttpURLConnection conn = (HttpURLConnection) url.openConnection();  //获取链接的对象
  6.                         conn.setRequestMethod("POST");
  7.                         conn.setConnectTimeout(5000);
  8.                         conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
  9.                         conn.setRequestProperty("Content-Length", data.length()+"");
  10.                         conn.setDoOutput(true);
  11.                         conn.getOutputStream().write(data.getBytes());  //获取输出流,将data的参数发出去
  12.                        
  13.                         int code = conn.getResponseCode();  //接收返回码
  14.                        
  15.                         if(code == 200)
  16.                         {
  17.                                 InputStream is = conn.getInputStream();   //通过链接对象获得输入流
  18.                                 return new String(loadDate(is),"GBK");
  19.                         }
复制代码

2.用HttpClient实现:
GET请求:
  1. String path = "http://192.168.0.115:8080/qqServer/loginServlet?username=" +
  2.                                         URLEncoder.encode(username,"utf-8") + "&password=" + URLEncoder.encode(password,"utf-8");
  3.                         HttpClient client = new DefaultHttpClient();
  4.                         HttpGet httpGet = new HttpGet(path);
  5.                         HttpResponse response = client.execute(httpGet);
  6.                        
  7.                         int code = response.getStatusLine().getStatusCode();
  8.                        
  9.                         if(code == 200)
  10.                         {
  11.                                 InputStream is = response.getEntity().getContent();
  12.                                 return new String(loadDate(is), "GBK");
  13.                         }
复制代码
POST请求:
  1. String path = "http://192.168.0.115:8080/qqServer/loginServlet";
  2.                         HttpClient client=new DefaultHttpClient();
  3.                         //创建请求路径的HttpGet对象
  4.                         HttpPost httpPost=new HttpPost(path);   
  5.                        
  6.                         //建立一个List集合,集合中的类型为NameVluePair对象
  7.                         List<NameValuePair> list=new ArrayList<NameValuePair>();
  8.                         list.add(new BasicNameValuePair("username",username));
  9.                         list.add(new BasicNameValuePair("password",password));
  10.                         UrlEncodedFormEntity entity=new UrlEncodedFormEntity(list,"utf-8");
  11.                         //设置实体数据
  12.                         httpPost.setEntity(entity);
  13.                         //让HttpClient往服务器发送数据
  14.                         HttpResponse response=client.execute(httpPost);
  15.                         //找到服务返回的状态码 200表示成功
  16.                         int code=response.getStatusLine().getStatusCode();
  17.                         if(code==200)
  18.                         {
  19.                                 InputStream is=response.getEntity().getContent();
  20.                                 return new String(loadDate(is),"GBK");
  21.                         }
复制代码
还有就是上面的方法可以通过开一个子线程,再接收返回来的数据,再将这个数据以消息的形式传给主线程,
这样的话,主线程就不会容易造成主线程的堵塞问题:
  1. new Thread()
  2.                 {
  3.                         public void run()
  4.                         {
  5.                                 String data = SendDataUtils.HttpPostSendData(username, password);
  6.                                 if(data != null)
  7.                                 {
  8.                                         Message msg = Message.obtain();
  9.                                         msg.what = 1;
  10.                                         msg.obj = data;
  11.                                         handler.sendMessage(msg);
  12.                                 }
  13.                         }
  14.                 }.start();
复制代码

恩~~ 以上就是普通的实现方法,可是还有一种更加简单的实现方法就是,利用网上的一个开源框架来实现;
这需要在网上下载这个jar文件:android-async-http-1.4.5.jar;值得注意的是这个开源框架是基于阿帕奇服务的!!

其主要实现的代码如下:
GET请求的实现:
  1. String url = "http://192.168.0.115:8080/qqServer/loginServlet?username=" +
  2.                                         URLEncoder.encode(username,"utf-8") + "&password="+URLEncoder.encode(password,"utf-8");
  3.                         AsyncHttpClient client = new AsyncHttpClient();
  4.                         client.get(url, new AsyncHttpResponseHandler() {
  5.                                
  6.                                 @Override
  7.                                 public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
  8.                                         // TODO Auto-generated method stub
  9.                                         try
  10.                                         {
  11.                                                 Toast.makeText(MainActivity.this, new String(arg2,"GBK"), 0).show();
  12.                                         }catch(Exception e)
  13.                                         {
  14.                                                 e.printStackTrace();
  15.                                         }
  16.                                 }
  17.                                
  18.                                 @Override
  19.                                 public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
  20.                                         // TODO Auto-generated method stub
  21.                                        
  22.                                 }
  23.                         });
复制代码
POST请求的实现:
  1. String url = "http://192.168.0.115:8080/qqServer/loginServlet";
  2.                        
  3.                                 username = URLEncoder.encode(username,"utf-8");
  4.                                 password = URLEncoder.encode(password,"utf-8");
  5.                                 AsyncHttpClient client = new AsyncHttpClient();   //异步http
  6.                                 RequestParams params = new RequestParams();   //请求参数
  7.                                 params.put("username", username);     //将用户名设置进去
  8.                                 params.put("password", password);
  9.                                 client.post(url, params,new AsyncHttpResponseHandler() {   //调用post方法
  10.                                        
  11.                                         @Override
  12.                                         public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {   //回调方法
  13.                                                 // TODO Auto-generated method stub
  14.                                                 try
  15.                                                 {
  16.                                                         Toast.makeText(MainActivity.this, new String(arg2,"GBK"), 0).show();
  17.                                                 }catch(Exception e)
  18.                                                 {
  19.                                                         e.printStackTrace();
  20.                                                 }
  21.                                         }
  22.                                        
  23.                                         @Override
  24.                                         public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
  25.                                                 // TODO Auto-generated method stub
  26.                                                
  27.                                         }
  28.                                 });
复制代码

QQ截图20141107195737.png






登录验证源码.zip

1.28 MB, 下载次数: 586

登录验证源码

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2014-11-8 18:55:11 | 显示全部楼层
:loveliness:既然进来了就要留脚印
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 1 反对 0

使用道具 举报

发表于 2014-11-8 23:46:38 | 显示全部楼层
支持下玄玄~
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2015-7-31 11:44:37 | 显示全部楼层
请问下那个HTTPCLIENT 的url地址怎么请求的,我用android studio请求整天无法请求过去
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2016-1-30 15:23:57 | 显示全部楼层
哇 ,求 服务端教程
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-26 17:09

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表