欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android客户端与服务端交互

程序员文章站 2024-02-16 12:52:22
本文和大家一起了解了一下android客户端与服务端是怎样交互的,具体内容如下 1.后台使用简单的servlet,支持get或post。这个servlet最终返回给前...

本文和大家一起了解了一下android客户端与服务端是怎样交互的,具体内容如下

1.后台使用简单的servlet,支持get或post。这个servlet最终返回给前台一个字符串flag,值是true或false,表示登录是否成功。

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

我是在myeclipse上创建的一个web service 项目,然后部署到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>

 
 

 

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 android: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">

 

  <textview android: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登陆示例">

 

  <edittext android: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>

 

  <edittext android: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"><button android: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>

 
 

 

<relativelayout android: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">

 

  <textview android: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请求。

 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 服务器响应字符串

   * @throws exception

   */

  public static string getrequest(string url) throws exception {

    // 创建httpget对象。

    httpget get = new httpget(url);

    // 发送get请求

    httpresponse httpresponse = httpclient.execute(get);

    // 如果服务器成功地返回响应

    if (httpresponse.getstatusline().getstatuscode() == 200) {

      // 获取服务器响应字符串

      string result = entityutils.tostring(httpresponse.getentity());

      return result;

    } else {

      log.d(服务器响应代码, (new integer(httpresponse.getstatusline()

          .getstatuscode())).tostring());

      return null;

    }

  }

 

  /**

   *

   * @param url

   *      发送请求的url

   * @param params

   *      请求参数

   * @return 服务器响应字符串

   * @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);

    // 如果服务器成功地返回响应

    if (httpresponse.getstatusline().getstatuscode() == 200) {

      // 获取服务器响应字符串

      string result = entityutils.tostring(httpresponse.getentity());

      return result;

    }

    return null;

  }

}

</namevaluepair></namevaluepair></string,>



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获取主线程传来的用户名和密码字符串 

    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(服务器返回值, strflag); 

    } catch (exception e) { 

      // todo auto-generated catch block 

      e.printstacktrace(); 

    } 

      

    if(strflag.trim().equals(true)){ 

      return true; 

    }else{ 

      return false; 

    } 

      

  } 

}

</string,></string,>

5.在androidmanifest.xml中注册intentservice。注意uses-permission节点,为程序开启访问网络的权限。 

<!--?xml version=1.0 encoding=utf-8?-->

<manifest android:versioncode="1" android:versionname="1.0" package="com.example.logindemo" xmlns:android="http://schemas.android.com/apk/res/android">

 

  <uses-sdk android:minsdkversion="8" android:targetsdkversion="18">

 

  <uses-permission android:name="android.permission.internet">

 

   

     

      <intent-filter>

         

 

        <category android:name="android.intent.category.launcher">

      </category></action></intent-filter>

    </activity>

     

    </activity>

 

    <service android:name="com.example.logindemo.connectservice">

    </service>

  </application>

 

</uses-permission></uses-sdk></manifest>

6.登陆界面处理,注意

按钮监听事件中,使用intent将要传递的值传给service。接收广播类中,同样使用intent将要传递的值传给下一个activity。在oncreate()中,动态注册接收广播类的实例receiver。在接收广播类中,不要使用完毕后忘记注销接收器,否则会报一个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;

  }

 

}

以上就是本文的全部内容,希望对大家的学习有所帮助。