Android客户端与服务端交互
本文和大家一起了解了一下android客户端与服务端是怎样交互的,具体内容如下
1.后台使用简单的servlet,支持GET或POST。这个servlet最终返回给前台一个字符串flag,值是true或false,表示登录是否成功。
servlet使用之前需要配置,主义servlet的servlet-name要和servlet-mapping的servlet-name一致,否则找不到路径
我是在myEclipse上创建的一个webservice项目,然后部署到tomcat服务器上以便android客户端访问
<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>
importjava.io.IOException;
importjava.io.PrintWriter;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importjavax.servlet.http.HttpSession;
importcom.zhongzhong.wap.bean.UserBean;
publicclassHelloServletextendsHttpServlet{
@Override
protectedvoiddoGet(HttpServletRequestreq,HttpServletResponseresp)
throwsServletException,IOException{
doPost(req,resp);
}
@Override
protectedvoiddoPost(HttpServletRequestreq,HttpServletResponseresp)
throwsServletException,IOException{
resp.setContentType(text/html);
PrintWriterout=resp.getWriter();
Booleanflag=false;
StringuserName=req.getParameter(un);
Stringpassword=req.getParameter(pw);
if(userName.equals(htp)&&password.equals(123))
{
flag=true;
}
elseflag=false;
System.out.println(userName:+userName+password:+password);
out.print(flag);
out.flush();
out.close();
}
}
2.然后我是在安卓的ADT上创建一个安卓项目,建立两个Activity,分别作为登录界面和登录成功界面。
<relativelayoutandroid:layout_height="match_parent"android:layout_width="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"xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"> <textviewandroid:id="@+id/textView1"android:layout_alignparenttop="true"android:layout_centerhorizontal="true"android:layout_height="wrap_content"android:layout_margintop="40dp"android:layout_width="wrap_content"android:text="HelloWorld登陆示例"> <edittextandroid:ems="10"android:hint="请输入账号"android:id="@+id/et_user"android:layout_below="@+id/textView1"android:layout_centerhorizontal="true"android:layout_height="wrap_content"android:layout_margintop="33dp"android:layout_width="wrap_content"> <requestfocus> </requestfocus></edittext> <edittextandroid:ems="10"android:hint="请输入密码"android:id="@+id/et_psw"android:inputtype="textPassword"android:layout_below="@+id/et_user"android:layout_centerhorizontal="true"android:layout_height="wrap_content"android:layout_margintop="40dp"android:layout_width="wrap_content"><buttonandroid:id="@+id/btn_login"android:layout_below="@+id/et_psw"android:layout_centerhorizontal="true"android:layout_height="wrap_content"android:layout_margintop="37dp"android:layout_width="wrap_content"android:text="登陆"></button></edittext></textview></relativelayout> <relativelayoutandroid:layout_height="match_parent"android:layout_width="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"xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"> <textviewandroid:layout_alignparenttop="true"android:layout_centerhorizontal="true"android:layout_height="wrap_content"android:layout_margintop="46dp"android:layout_width="wrap_content"android:text="登陆成功"> </textview></relativelayout>
3.HTTP的访问公共类,用于处理GET和POST请求。
packagecom.example.logindemo;
importjava.util.ArrayList;
importjava.util.List;
importjava.util.Map;
importorg.apache.http.HttpResponse;
importorg.apache.http.NameValuePair;
importorg.apache.http.client.HttpClient;
importorg.apache.http.client.entity.UrlEncodedFormEntity;
importorg.apache.http.client.methods.HttpGet;
importorg.apache.http.client.methods.HttpPost;
importorg.apache.http.impl.client.DefaultHttpClient;
importorg.apache.http.message.BasicNameValuePair;
importorg.apache.http.util.EntityUtils;
importandroid.content.Entity;
importandroid.util.Log;
publicclassHttpUtil{
//创建HttpClient对象
publicstaticHttpClienthttpClient=newDefaultHttpClient();
publicstaticfinalStringBASE_URL=http://192.168.3.14:8090/HelloWord/;
/**
*
*@paramurl
*发送请求的URL
*@return服务器响应字符串
*@throwsException
*/
publicstaticStringgetRequest(Stringurl)throwsException{
//创建HttpGet对象。
HttpGetget=newHttpGet(url);
//发送GET请求
HttpResponsehttpResponse=httpClient.execute(get);
//如果服务器成功地返回响应
if(httpResponse.getStatusLine().getStatusCode()==200){
//获取服务器响应字符串
Stringresult=EntityUtils.toString(httpResponse.getEntity());
returnresult;
}else{
Log.d(服务器响应代码,(newInteger(httpResponse.getStatusLine()
.getStatusCode())).toString());
returnnull;
}
}
/**
*
*@paramurl
*发送请求的URL
*@paramparams
*请求参数
*@return服务器响应字符串
*@throwsException
*/
publicstaticStringpostRequest(Stringurl,Map<string,string="">rawParams)
throwsException{
//创建HttpPost对象。
HttpPostpost=newHttpPost(url);
//如果传递参数个数比较多的话可以对传递的参数进行封装
List<namevaluepair>params=newArrayList<namevaluepair>();
for(Stringkey:rawParams.keySet()){
//封装请求参数
params.add(newBasicNameValuePair(key,rawParams.get(key)));
}
//设置请求参数
post.setEntity(newUrlEncodedFormEntity(params,UTF-8));
//发送POST请求
HttpResponsehttpResponse=httpClient.execute(post);
//如果服务器成功地返回响应
if(httpResponse.getStatusLine().getStatusCode()==200){
//获取服务器响应字符串
Stringresult=EntityUtils.toString(httpResponse.getEntity());
returnresult;
}
returnnull;
}
}
</namevaluepair></namevaluepair></string,>
4.IntentService服务,用于在后台以队列方式处理耗时操作。
packagecom.example.logindemo;
importjava.util.HashMap;
importandroid.app.IntentService;
importandroid.content.Intent;
importandroid.util.Log;
publicclassConnectServiceextendsIntentService{
privatestaticfinalStringACTION_RECV_MSG=com.example.logindemo.action.RECEIVE_MESSAGE;
publicConnectService(){
super(TestIntentService);
//TODOAuto-generatedconstructorstub
}
@Override
protectedvoidonHandleIntent(Intentintent){
//TODOAuto-generatedmethodstub
/**
*经测试,IntentService里面是可以进行耗时的操作的
*IntentService使用队列的方式将请求的Intent加入队列,
*然后开启一个workerthread(线程)来处理队列中的Intent
*对于异步的startService请求,IntentService会处理完成一个之后再处理第二个
*/
Booleanflag=false;
//通过intent获取主线程传来的用户名和密码字符串
Stringusername=intent.getStringExtra(username);
Stringpassword=intent.getStringExtra(password);
flag=doLogin(username,password);
Log.d(登录结果,flag.toString());
IntentbroadcastIntent=newIntent();
broadcastIntent.setAction(ACTION_RECV_MSG);
broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
broadcastIntent.putExtra(result,flag.toString());
sendBroadcast(broadcastIntent);
}
//定义发送请求的方法
privateBooleandoLogin(Stringusername,Stringpassword)
{
StringstrFlag=;
//使用Map封装请求参数
HashMap<string,string="">map=newHashMap<string,string="">();
map.put(un,username);
map.put(pw,password);
//定义发送请求的URL
Stringurl=HttpUtil.BASE_URL+queryOrder?un=+username+&pw=+password;//GET方式
//Stringurl=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(服务器返回值,strFlag);
}catch(Exceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
if(strFlag.trim().equals(true)){
returntrue;
}else{
returnfalse;
}
}
}
</string,></string,>
5.在AndroidManifest.xml中注册IntentService。注意uses-permission节点,为程序开启访问网络的权限。
<!--?xmlversion=1.0encoding=utf-8?--> <manifestandroid:versioncode="1"android:versionname="1.0"package="com.example.logindemo"xmlns:android="http://schemas.android.com/apk/res/android"> <uses-sdkandroid:minsdkversion="8"android:targetsdkversion="18"> <uses-permissionandroid:name="android.permission.INTERNET"> <intent-filter> <categoryandroid:name="android.intent.category.LAUNCHER"> </category></action></intent-filter> </activity> </activity> <serviceandroid:name="com.example.logindemo.ConnectService"> </service> </application> </uses-permission></uses-sdk></manifest>
6.登陆界面处理,注意
按钮监听事件中,使用Intent将要传递的值传给service。接收广播类中,同样使用Intent将要传递的值传给下一个Activity。在onCreate()中,动态注册接收广播类的实例receiver。在接收广播类中,不要使用完毕后忘记注销接收器,否则会报一个AreyoumissingacalltounregisterReceiver()?的异常。
packagecom.example.logindemo;
importandroid.os.Bundle;
importandroid.app.Activity;
importandroid.content.BroadcastReceiver;
importandroid.content.Context;
importandroid.content.Intent;
importandroid.content.IntentFilter;
importandroid.util.Log;
importandroid.view.Menu;
importandroid.view.View;
importandroid.view.View.OnClickListener;
importandroid.widget.Button;
importandroid.widget.EditText;
importandroid.widget.Toast;
publicclassMainActivityextendsActivity{
privatestaticfinalStringACTION_RECV_MSG=com.example.logindemo.action.RECEIVE_MESSAGE;
privateButtonloginBtn;
privateEditTextet_username;
privateEditTextet_password;
privateStringuserName;
privateStringpassWord;
privateMessageReceiverreceiver;
@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
//动态注册receiver
IntentFilterfilter=newIntentFilter(ACTION_RECV_MSG);
filter.addCategory(Intent.CATEGORY_DEFAULT);
receiver=newMessageReceiver();
registerReceiver(receiver,filter);
}
privatevoidinitView(){
//TODOAuto-generatedmethodstub
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(newOnClickListener(){
@Override
publicvoidonClick(Viewv){
//TODOAuto-generatedmethodstub
if(matchLoginMsg())
{
//如果校验成功
IntentmsgIntent=newIntent(MainActivity.this,ConnectService.class);
msgIntent.putExtra(username,et_username.getText().toString().trim());
msgIntent.putExtra(password,et_password.getText().toString().trim());
startService(msgIntent);
}
}
});
}
protectedbooleanmatchLoginMsg(){
//TODOAuto-generatedmethodstub
userName=et_username.getText().toString().trim();
passWord=et_password.getText().toString().trim();
if(userName.equals())
{
Toast.makeText(MainActivity.this,账号不能为空,Toast.LENGTH_SHORT).show();
returnfalse;
}
if(passWord.equals())
{
Toast.makeText(MainActivity.this,密码不能为空,Toast.LENGTH_SHORT).show();
returnfalse;
}
returntrue;
}
//接收广播类
publicclassMessageReceiverextendsBroadcastReceiver{
@Override
publicvoidonReceive(Contextcontext,Intentintent){
Stringmessage=intent.getStringExtra(result);
Log.i(MessageReceiver,message);
//如果登录成功
if(message.equals(true)){
//启动MainActivity
IntentnextIntent=newIntent(MainActivity.this,NaviActivity.class);
startActivity(nextIntent);
//结束该Activity
finish();
//注销广播接收器
context.unregisterReceiver(this);
}else{
Toast.makeText(MainActivity.this,用户名或密码错误,请重新输入!,Toast.LENGTH_SHORT).show();
}
}
}
@Override
publicbooleanonCreateOptionsMenu(Menumenu){
//Inflatethemenu;thisaddsitemstotheactionbarifitispresent.
getMenuInflater().inflate(R.menu.main,menu);
returntrue;
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助。