今天了解了一下androidclient与服务端是如何交互的,发现事实上跟web有点类似吧,然后网上找了大神的登陆演示样例。是基于IntentService的

1.后台使用简单的servlet,支持GET或POST。

这个servlet终于返回给前台一个字符串flag,值是true或false,表示登录是否成功。

servlet使用之前须要配置。主义servlet的servlet-name要和servlet-mapping的servlet-name一致。否则找不到路径

我是在myEclipse上创建的一个web service 项目。然后部署到tomcatserver上以便androidclient訪问

<servlet>
<servlet-name>helloWorld</servlet-name>
<servlet-class>com.zhongzhong.wap.action.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>helloWorld</servlet-name>
<url-pattern>/queryOrder</url-pattern>
</servlet-mapping>

import java.io.IOException;
import java.io.PrintWriter; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; import com.zhongzhong.wap.bean.UserBean; public class HelloServlet extends HttpServlet { @Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException { resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
Boolean flag = false;
String userName = req.getParameter("un");
String password = req.getParameter("pw");
if(userName.equals("htp")&&password.equals("123"))
{
flag = true;
} else flag = false;
System.out.println("userName:"+userName+" password:"+password);
out.print(flag);
out.flush();
out.close();
} }

2.然后我是在安卓的ADT上创建一个安卓项目。建立两个Activity,分别作为登录界面和登录成功界面。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" > <TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:text="HelloWorld登陆演示样例" /> <EditText
android:id="@+id/et_user"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="33dp"
android:ems="10"
android:hint="请输入账号" > <requestFocus />
</EditText> <EditText
android:id="@+id/et_psw"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/et_user"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:ems="10"
android:hint="请输入password"
android:inputType="textPassword" /> <Button
android:id="@+id/btn_login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/et_psw"
android:layout_centerHorizontal="true"
android:layout_marginTop="37dp"
android:text="登陆" /> </RelativeLayout>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".NaviActivity" > <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="46dp"
android:text="登陆成功" /> </RelativeLayout>

3.HTTP的訪问公共类,用于处理GET和POST请求

package com.example.logindemo;

import java.util.ArrayList;
import java.util.List;
import java.util.Map; import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils; import android.content.Entity;
import android.util.Log; public class HttpUtil {
// 创建HttpClient对象
public static HttpClient httpClient = new DefaultHttpClient();
public static final String BASE_URL = "http://192.168.3.14:8090/HelloWord/"; /**
*
* @param url
* 发送请求的URL
* @return server响应字符串
* @throws Exception
*/
public static String getRequest(String url) throws Exception {
// 创建HttpGet对象。
HttpGet get = new HttpGet(url);
// 发送GET请求
HttpResponse httpResponse = httpClient.execute(get);
// 假设server成功地返回响应
if (httpResponse.getStatusLine().getStatusCode() == 200) {
// 获取server响应字符串
String result = EntityUtils.toString(httpResponse.getEntity());
return result;
} else {
Log.d("server响应代码", (new Integer(httpResponse.getStatusLine()
.getStatusCode())).toString());
return null;
}
} /**
*
* @param url
* 发送请求的URL
* @param params
* 请求參数
* @return server响应字符串
* @throws Exception
*/
public static String postRequest(String url, Map<String, String> rawParams)
throws Exception {
// 创建HttpPost对象。 HttpPost post = new HttpPost(url);
// 假设传递參数个数比較多的话能够对传递的參数进行封装
List<NameValuePair> params = new ArrayList<NameValuePair>();
for (String key : rawParams.keySet()) {
// 封装请求參数
params.add(new BasicNameValuePair(key, rawParams.get(key)));
}
// 设置请求參数
post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
// 发送POST请求
HttpResponse httpResponse = httpClient.execute(post);
// 假设server成功地返回响应
if (httpResponse.getStatusLine().getStatusCode() == 200) {
// 获取server响应字符串
String result = EntityUtils.toString(httpResponse.getEntity());
return result;
}
return null;
}
}

4.IntentService服务,用于在后台以队列方式处理耗时操作。

package com.example.logindemo;

import java.util.HashMap;

import android.app.IntentService;
import android.content.Intent;
import android.util.Log; public class ConnectService extends IntentService {
private static final String ACTION_RECV_MSG = "com.example.logindemo.action.RECEIVE_MESSAGE"; public ConnectService() {
super("TestIntentService");
// TODO Auto-generated constructor stub
} @Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
/**
* 经測试。IntentService里面是能够进行耗时的操作的
* IntentService使用队列的方式将请求的Intent增加队列,
* 然后开启一个worker thread(线程)来处理队列中的Intent
* 对于异步的startService请求,IntentService会处理完毕一个之后再处理第二个
*/
Boolean flag = false;
//通过intent获取主线程传来的username与password字符串
String username = intent.getStringExtra("username");
String password = intent.getStringExtra("password");
flag = doLogin(username, password);
Log.d("登录结果", flag.toString()); Intent broadcastIntent = new Intent();
broadcastIntent.setAction(ACTION_RECV_MSG);
broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
broadcastIntent.putExtra("result", flag.toString());
sendBroadcast(broadcastIntent); } // 定义发送请求的方法
private Boolean doLogin(String username, String password)
{
String strFlag = "";
// 使用Map封装请求參数
HashMap<String, String> map = new HashMap<String, String>();
map.put("un", username);
map.put("pw", password);
// 定义发送请求的URL
String url = HttpUtil.BASE_URL + "queryOrder?un=" + username + "&pw=" + password; //GET方式
// String url = HttpUtil.BASE_URL + "LoginServlet"; //POST方式
Log.d("url", url);
Log.d("username", username);
Log.d("password", password);
try {
// 发送请求
strFlag = HttpUtil.postRequest(url, map); //POST方式
// strFlag = HttpUtil.getRequest(url); //GET方式
Log.d("server返回值", strFlag);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} if(strFlag.trim().equals("true")){
return true;
}else{
return false;
} }
}

5。

在AndroidManifest.xml中注冊IntentService。

注意uses-permission节点。为程序开启訪问网络的权限。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.logindemo"
android:versionCode="1"
android:versionName="1.0" > <uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" /> <uses-permission android:name="android.permission.INTERNET" /> <application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.logindemo.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.logindemo.NaviActivity"
android:label="@string/title_activity_navi" >
</activity> <service android:name="com.example.logindemo.ConnectService" >
</service>
</application> </manifest>

6.登陆界面处理,注意

  1. button监听事件中。使用Intent将要传递的值传给service。

  2. 接收广播类中,相同使用Intent将要传递的值传给下一个Activity。
  3. 在onCreate()中,动态注冊接收广播类的实例receiver。
  4. 在接收广播类中,不要使用完成后忘记注销接收器。否则会报一个Are you missing a call to unregisterReceiver()?

    的异常。

package com.example.logindemo;

import android.os.Bundle;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast; public class MainActivity extends Activity {
private static final String ACTION_RECV_MSG = "com.example.logindemo.action.RECEIVE_MESSAGE";
private Button loginBtn;
private EditText et_username;
private EditText et_password;
private String userName;
private String passWord;
private MessageReceiver receiver ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
//动态注冊receiver
IntentFilter filter = new IntentFilter(ACTION_RECV_MSG);
filter.addCategory(Intent.CATEGORY_DEFAULT);
receiver = new MessageReceiver();
registerReceiver(receiver, filter);
} private void initView() {
// TODO Auto-generated method stub
et_username = (EditText)findViewById(R.id.et_user);
et_password =( EditText)findViewById(R.id.et_psw);
loginBtn = (Button)findViewById(R.id.btn_login);
loginBtn.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(matchLoginMsg())
{
// 假设校验成功
Intent msgIntent = new Intent(MainActivity.this, ConnectService.class);
msgIntent.putExtra("username", et_username.getText().toString().trim());
msgIntent.putExtra("password", et_password.getText().toString().trim());
startService(msgIntent);
} }
});
} protected boolean matchLoginMsg() {
// TODO Auto-generated method stub
userName = et_username.getText().toString().trim();
passWord = et_password.getText().toString().trim();
if(userName.equals(""))
{
Toast.makeText(MainActivity.this, "账号不能为空",Toast.LENGTH_SHORT).show();
return false;
}
if(passWord.equals(""))
{
Toast.makeText(MainActivity.this, "密码不能为空",Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
//接收广播类
public class MessageReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String message = intent.getStringExtra("result");
Log.i("MessageReceiver", message);
// 假设登录成功
if (message.equals("true")){
// 启动Main Activity
Intent nextIntent = new Intent(MainActivity.this, NaviActivity.class);
startActivity(nextIntent);
// 结束该Activity
finish();
//注销广播接收器
context.unregisterReceiver(this);
}else{
Toast.makeText(MainActivity.this, "用户名或密码错误,请又一次输入!",Toast.LENGTH_SHORT).show();
} }
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
} }

执行截图:

watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcXE1NDQ1Mjk1NjM=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="">

转载自http://blog.csdn.net/softwave

Androidclient与服务端交互之登陆演示样例的更多相关文章

  1. Android客户端与服务端交互之登陆示例

    Android客户端与服务端交互之登陆示例 今天了解了一下android客户端与服务端是怎样交互的,发现其实跟web有点类似吧,然后网上找了大神的登陆示例,是基于IntentService的 1.后台 ...

  2. 移动端报表JS开发演示样例

    近期对移动端的报表开发颇有研究,细磨精算了好久,尽管到如今还是"囊中羞涩",但决定还是先抛砖引玉,拿点小干货出来和大家分享. 研究的工具是比較有代表性的FineReport. 1. ...

  3. java客户端与服务端交互通用处理 框架解析

    一.综述 java 客户端与服务端交互过程中,采用NIO通讯是异步的,客户端基本采用同一处理范式,来进行同异步的调用处理. 处理模型有以下几个要素: 1. NIO发送消息后返回的Future 2. 每 ...

  4. IOS开发系列之阿堂教程:玩转IPhone客户端和Web服务端交互(客户端)实践

    说到ios的应用开发,我们不能不提到web server服务端,如果没有服务端的支持,ios应用开发就没有多大意义了,因为从事过手机开发的朋友都知道(Android也一样),大量复杂业务的处理和数据库 ...

  5. c++ 网络编程(一)TCP/UDP windows/linux 下入门级socket通信 客户端与服务端交互代码

    原文作者:aircraft 原文地址:https://www.cnblogs.com/DOMLX/p/9601511.html c++ 网络编程(一)TCP/UDP  入门级客户端与服务端交互代码 网 ...

  6. Android网络(3):HttpClient作client,Tomcat Servlet作server的交互演示样例

    前面相继介绍了Android网络编程里的Socket传输图片.HttpURLConnection,今天看HttpClient. 第一部分:JavaEE版的Eclipse配置Tomcat [备注:开发后 ...

  7. 百度地图 Android SDK - 检索功能使用的简单演示样例

    百度地图 SDK 不仅为广大开发人员提供了炫酷的地图展示效果.丰富的覆盖物图层,更为广大开发人员提供了多种 LBS 检索的能力. 通过这些接口,开发人员能够轻松的訪问百度的 LBS 数据,丰富自己的移 ...

  8. MapGuide应用程序演示样例——你好,MapGuide!

    图 3‑4显示了基于MapGuide的Web应用程序的开发流程,整个开发流程能够分为五个阶段.图中,矩形代表任务,椭圆形被任务使用的或被任务创建的实体,箭头代表数据流. 1) 载入文件类型的数据,配置 ...

  9. Thrift的安装和简单演示样例

    本文仅仅是简单的解说Thrift开源框架的安装和简单使用演示样例.对于具体的解说,后面在进行阐述. Thrift简述                                           ...

随机推荐

  1. 关于语义化版本(semantic versioning or SemVer)

    1  为什么要有SemVer? SemVer用来规范组件之间的依赖版本,它使用一个版本号来传递出组件的API的变化情况. 在理解这规范之后,看一眼依赖包的版本号,就知道API的变化(兼容性)程度,方便 ...

  2. [转]Java中堆和栈创建对象的区别

    转载自http://blog.csdn.net/hbhhww/article/details/8152838 栈与堆都是Java用来在Ram中存放数据的地方.与C++不同,Java自动管理栈和堆,程序 ...

  3. bootstrap使用前注意点和盒子模型

    bootstrap注意事项: https://getbootstrap.com/docs/4.0/getting-started/introduction/#quick-start 盒子模型: htt ...

  4. 二叉排序树实现(C++封装)

    设计思路 设计一个类,根结点只可读取,具备构造二叉树.插入结点.删除结点.查找. 查找最大值.查找最小值.查找指定结点的前驱和后继等功能接口. 二叉排序树概念 它或者是一棵空树:或者是具有下列性质的二 ...

  5. 牛客练习赛19 C-托米航空公司

    思路:轮廓线dp,找bug找死我了. #include<bits/stdc++.h> #define LL long long #define fi first #define se se ...

  6. [hdu3934] 凸包 旋转卡壳

    大致题意: 求多边形的最大内接三角形 旋转卡壳 模板题 #include<cstdio> #include<iostream> #include<cstring> ...

  7. 洛谷P4071 [SDOI2016] 排列计数 [组合数学]

    题目传送门 排列计数 题目描述 求有多少种长度为 n 的序列 A,满足以下条件: 1 ~ n 这 n 个数在序列中各出现了一次 若第 i 个数 A[i] 的值为 i,则称 i 是稳定的.序列恰好有 m ...

  8. LibreOJ#143 质数判定 [Miller_Rabin]

    题目传送门 质数判定 题目描述 判定输入的数是不是质数. 输入格式 若干行,一行一个数 x. 行数不超过 $1.5\times 10^4$ 输出格式 对于输入的每一行,如果 x是质数输出一行 Y,否则 ...

  9. EAP-MD5认证暴力破解工具eapmd5pass

    EAP-MD5认证暴力破解工具eapmd5pass   EAP-MD5是一种基于802.1x协议的认证机制.由于该机制存在漏洞,所以并不能保证数据安全.Kali Linux预置一个专用工具eapmd5 ...

  10. hiho1291(逆序思维,并查集)

    题目链接:[https://hihocoder.com/problemset/problem/1291] 题意:在<我的世界>游戏中放置沙盒,沙盒为体积为1的正方体,按顺序给你一些坐标,然 ...