Android Http简单使用实现登录校园网App

由于登录需要学校认证的WIFI比较繁琐,所以写了个小的App自己用,算是做笔记和试图养成一个写博客的习惯…

作为一个初学者,没有企业开发的经历,很多代码都是按照自己的思路来写,存在很多需要优化的方面,第二篇博客,经验不够,存在不足的地方,大神勿喷....

演示

布局文件(没有自定义View,就是简单的登录界面,完全可以不看)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:background="@drawable/main_back"android:fitsSystemWindows="true"android:orientation="vertical"tools:context="com.brioal.lzulogin.MainActivity"><LinearLayout
        android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_weight="1"android:orientation="vertical"><ImageView
            android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_gravity="center"android:layout_marginBottom="20dp"android:layout_weight="1"android:padding="20dp"android:src="@mipmap/ic_launcher" /><TextView
            android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_gravity="center"android:layout_weight="1"android:gravity="center"android:text="@string/main_title"android:textColor="@color/colorWhite"android:textSize="30dp"android:typeface="serif" /></LinearLayout><RelativeLayout
        android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_weight="1"android:background="@color/colorWhite"><LinearLayout
            android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_centerInParent="true"android:background="@color/colorWhite"android:orientation="vertical"><LinearLayout                android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_margin="10dp"android:orientation="horizontal"><android.support.design.widget.TextInputLayout
                    android:layout_width="0dp"android:layout_height="wrap_content"android:layout_weight="1"><EditText
                        android:inputType="textAutoComplete"android:id="@+id/main_et_name"android:layout_width="match_parent"android:layout_height="wrap_content"android:hint="@string/username"android:imeOptions="actionNext"android:typeface="serif" /></android.support.design.widget.TextInputLayout><TextView
                    android:layout_width="wrap_content"android:layout_height="match_parent"android:layout_marginLeft="10dp"android:gravity="center"android:text="@string/lzu_edu_cn"android:textSize="20dp"android:typeface="serif" /></LinearLayout><android.support.design.widget.TextInputLayout
                android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_margin="10dp"><EditText                    android:imeOptions="actionDone"android:id="@+id/main_et_password"android:layout_width="match_parent"android:layout_height="wrap_content"android:hint="@string/password"android:inputType="textPassword"android:typeface="serif" /></android.support.design.widget.TextInputLayout><Button
                android:id="@+id/main_btn_save"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_gravity="center"android:layout_margin="20dp"android:background="@drawable/btn_back"android:text="保存"android:textColor="@color/colorAccent"android:typeface="serif" /></LinearLayout></RelativeLayout></LinearLayout>

实现原理

1.使用Http的Get请求,传入用户名和密码,获取返回的网页代码,通过代码内容来判断登录的结果
2.使用Receiver,监听WIFI连接状态的改变,当连接上一个可用的WIFI之后调用方法进行登录(因为学校大部分WIFI还是需要登陆的,所以没做过多的判断,对所有WIFI都进行登录操作);
3.获取网页的返回内容.判断登录的结果(看过返回网页的代码,没有其他判断语句,包含连接成功的网页就是登录成功,包含用户名或者密码的内容就是错误返回,所以偷懒直接判断网页源代码是否包含那几个字符串,具体情况需要具体分析)

部分用到的方法的解释

1.获取网页的返回内容 通过链接打开InputStream,读取数据返回字符串

应该都能看懂,就不做解释

public static String getHtml(InputStream inputStream, String encode) {InputStream is = inputStream;String code = encode;BufferedReader reader = null;StringBuffer sb = null;try {reader = new BufferedReader(new InputStreamReader(inputStream, encode));sb = new StringBuffer();String str = null;while ((str = reader.readLine()) != null) {if (str.isEmpty()) {} else {sb.append(str);sb.append("\n");}}reader.close();} catch (UnsupportedEncodingException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return sb.toString();}

2.注册能监听WIFI状态的BroadcastReceiver  
使用静态注册方法,这样即使App不启动也能响应事件
我使用的是小米手机,安全中心内会默认禁止软件的自动启动和系统唤醒,需要关闭之后Receiver才会响应事件

Receiver继承BroadcastReceiver

public class LoginReceiver extends BroadcastReceiver {@Overridepublic void onReceive(final Context context, Intent intent) {...}

Manifes文件中对Receiver进行注册

 <receiver android:name=".receiver.LoginReceiver"><intent-filter><action android:name="android.net.conn.CONNECTIVITY_CHANGE" /><action android:name="android.net.wifi.WIFI_STATE_CHANGED" /><action android:name="android.net.wifi.STATE_CHANGE" /></intent-filter></receiver>

3.在onReceiver方法中对intent.getAction()进行判断

if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(intent.getAction())) {final Parcelable parcelableExtra = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);if (null != parcelableExtra) {NetworkInfo networkInfo = (NetworkInfo) parcelableExtra;NetworkInfo.State state = networkInfo.getState();boolean isConnected = state == NetworkInfo.State.CONNECTED;if (isConnected) {Log.i(TAG, "onReceive: 连接上可用的WIFi");// 开始登录} else {Log.i(TAG, "onReceive: 未连接可用wifi");}}}

4.通过从FireDebug中获取到的点击登录按钮的响应连接和传入参数来进行登录操作 

String click_url = "..........";
String parma = "...........";
HttpURLConnection connection = null;URL url;try {url = new URL(click_url);connection = (HttpURLConnection) url.openConnection();connection.setDoInput(true);connection.setDoOutput(true);connection.setRequestMethod("GET");connection.setUseCaches(false);connection.getOutputStream().write(parma.getBytes());connection.connect(); //????int responseCode = connection.getResponseCode();if (responseCode == HttpURLConnection.HTTP_OK) {//获取网页传回的数据String s = getHtml(connection.getInputStream(), "GBK");//此处测试的时候因为错误页面只返回几个字,所以格式于之前的登录成功的格式不同,改为UTF-8之后不会乱码String errorMsg = new String(s.getBytes("GBK"), "UTF-8");System.out.println("Html" + s);if (s.contains("连接成功")) {//使用Handler来更新界面handler.sendEmptyMessage(MainActivity.RESULT_SUCCESS);} else if (errorMsg.contains("密码错误")) {//密码错误handler.sendEmptyMessage(MainActivity.RESULT_PASSWORD_ERROT);} else if (errorMsg.contains("用户名错误")) {handler.sendEmptyMessage(MainActivity.RESULT_NAME_ERROT);}connection.disconnect();}} catch (MalformedURLException e) {e.printStackTrace();} catch (ProtocolException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}

5.Handler接收消息显示通知或者更新布局
Activity前台的时候使用的是MainActiivty传入的Handler,负责更新登录按钮的显示文字
当Activity不在前台的时候,使用的是Receiver内的Handler,负责显示通知

Receiver内的Handler

    public Handler handler = new Handler() {@Overridepublic void handleMessage(Message msg) {super.handleMessage(msg);if (msg.what == RESULT_SUCCESS) {showSuccess();} else if (msg.what == RESULT_NAME_ERROT) {showErron("用户名错误");} else if (msg.what == RESULT_PASSWORD_ERROT) {showErron("密码错误");}}};

显示登录成功的通知

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)public void showSuccess() {//获取NoticationManager对象manager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);final Notification notify3 = new Notification.Builder(context).setSmallIcon(R.mipmap.ic_launcher) // 设置图标.setTicker("登录成功") // 设置在通知栏上滚动的信息.setContentTitle("登陆成功") // 设置主标题.build();notify3.flags |= Notification.FLAG_AUTO_CANCEL; // 点击自动消失notify3.defaults |= Notification.DEFAULT_VIBRATE; //使用自动的振动模式manager.notify(NOTICATION_CANCLE_DELAY, notify3); // 显示通知}

显示错误的通知 (内容大同小异) ,不同的是设置了点击的时候启动MainActivity

 @TargetApi(Build.VERSION_CODES.JELLY_BEAN)public void showErron(String msg) {manager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);PendingIntent pendingIntent3 = PendingIntent.getActivity(context, 0,new Intent(context, MainActivity.class), 0);Notification notify3 = new Notification.Builder(context).setSmallIcon(R.mipmap.ic_launcher).setTicker("登录失败").setContentTitle("登陆失败").setContentText(msg).setContentIntent(pendingIntent3).build();notify3.flags |= Notification.FLAG_AUTO_CANCEL;manager.notify(NOTICATION_CANCLE_DELAY, notify3);}

至于MainActivity的代码都比较简单,因为宿舍要熄灯了,而且我感觉不会有多少人看吧,暂且不更新了,总结写的有点乱,等找个时候再重新整理一遍遇到的问题和解决思路.
源码已分享到Github
欢迎交流Android开发,大三狗一枚,联系方式:QQ:821329382

Android Http简单使用实现登录校园网App相关推荐

  1. Android实现简单账号密码登录

    写在了线程池里边. public static final ExecutorService fixedThreadPool = Executors.newFixedThreadPool(8); //登 ...

  2. Android——一个简单的APP模版

    Android--一个简单的APP模版 述 效果视频 技术栈 地图.定位.导航 地图 定位 导航 偏好设置 当前导航信息 预定车位和订单结算 创建订单 计时服务传导 后台服务计时 订单结算 个人信息 ...

  3. Android实现二维码登录的简单实现

    在Android app的开发中,完成一个二维码登录的功能可以帮助我们的了解前后端与Android的简单交互过程,在此做一个简单的登录测试.涉及到简单的PHP的使用以及XAMPP的使用. 1.实现二维 ...

  4. 简单Android手机APP地图,android最简单手机地图APP(只需5分钟)

    android最简单手机地图APP--只有三部分. 第一部分 首先建立一个MapActivity在setContentView(R.layout.activity_map);中创建一个代码如下. [h ...

  5. android ui 录音机,盘点:简单好用的录音APP有哪些?

    原标题:盘点:简单好用的录音APP有哪些? 本文为「智活范」原创作品,欢迎关注我们! 前段时间去跟一个采访,因为过程中要录音,遂找人介绍了一款录音APP来用.当时用下来觉得录音体验没问题,但就是界面太 ...

  6. android ios 录音功能,盘点:简单好用的录音APP有哪些?

    原标题:盘点:简单好用的录音APP有哪些? 本文为「智活范」原创作品,欢迎关注我们! 前段时间去跟一个采访,因为过程中要录音,遂找人介绍了一款录音APP来用.当时用下来觉得录音体验没问题,但就是界面太 ...

  7. Android studio课程设计开发实现---日记APP

    Android studio课程设计开发实现-日记APP 文章目录 Android studio课程设计开发实现---日记APP 前言 一.效果 二.功能介绍 1.主要功能 2.涉及知识点 三.实现思 ...

  8. iOS/Android 微信及浏览器中唤起本地APP

    title: iOS/Android 微信及浏览器中唤起本地APP date: 2017-05-10 10:19:20 tags: 需求概述 分享应用活动链接已经成为手机应用一个非常重要的推广传播形式 ...

  9. Android 集成ShareSDK实现三方登录

    ** 前言 ** 三方登录在如今差不多已经成为每一款App必备的功能了.每次集成都会遇到各种各样的问题,今天总结一下三方登录的流程,以免忘记.现在好像还没有专门的三方登录SDK,ShareSDK和友盟 ...

最新文章

  1. 适配器模式理解和使用
  2. GBRT(GBDT)(MART)(Tree Net)(Tree link)
  3. 计算机组成原理:I/O的三大特性
  4. 为了OFFER,花了几个小时,刷下Leetcode链表算法题
  5. 1.15运行命令直至执行成功
  6. PHP学习笔记——Php文件引入
  7. Linux 设备驱动中的 I/O模型(二)—— 异步通知和异步I/O
  8. dropdownlist可以多选。类似的例子。。。
  9. 前序表达式 中序表达式 后序表达式
  10. C++ 平方、开方、取整运算
  11. 小猫爪:嵌入式小知识11-MPU详解及其应用
  12. github添加设置ssh key
  13. 为什么远程计算机后会黑屏,电脑上钉钉怎么远程,为什么远程后黑屏?
  14. Java多线程中wait, notify and notifyAll的使用
  15. Gabor特征码分析
  16. MAC上Chrome浏览器没有声音
  17. scrapy 抓取拉钩 ajax
  18. 设计模式五:原型模式
  19. C Primer Plus 第十二章 课后答案
  20. 仿八大行星绕太阳3D旋转效果

热门文章

  1. 精简版系统制作的关键技术
  2. 华东师大计算机、南大软件、国防科大智能夏令营面经
  3. java内存溢出怎么排查_java线上内存溢出问题排查步骤
  4. Java数据结构与Java算法上
  5. 《魔兽争霸3》魔兽攻防算法
  6. 我关于KMP算法的初步理解
  7. 用一台计算机操控另一台计算机关机的问题
  8. GDPU C语言 天码行空12
  9. 【设计模式】 - 结构型模式 - 享元模式
  10. ANTLR4 line 1:6 mismatched input ‘103‘ expecting GEN_NO