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

android 网络编程之网络通信几种方式实例分享

程序员文章站 2023-11-14 08:25:46
如今,手机应用渗透到各行各业,数量难以计数,其中大多数应用都会使用到网络,与服务器的交互势不可挡,那么android当中访问网络有哪些方式呢? 现在总结了六种方式: (...

如今,手机应用渗透到各行各业,数量难以计数,其中大多数应用都会使用到网络,与服务器的交互势不可挡,那么android当中访问网络有哪些方式呢?

现在总结了六种方式:


(1)针对tcp/ip的socket、serversocket

(2)针对udp的datagramsocket、datagrampackage。这里需要注意的是,考虑到android设备通常是手持终端,ip都是随着上网进行分配的。不是固定的。因此开发也是有一点与普通互联网应用有所差异的。

(3)针对直接url的httpurlconnection。

(4)google集成了apache http客户端,可使用http进行网络编程。

(5)使用webservice。android可以通过开源包如jackson去支持xmlrpc和jsonrpc,另外也可以用ksoap2去实现webservice。

(6)直接使用webview视图组件显示网页。基于webview 进行开发,google已经提供了一个基于chrome-lite的web浏览器,直接就可以进行上网浏览网页。

一、socket与serversocket

客户端代码

复制代码 代码如下:

public class testnetworkactivity extends activity implements onclicklistener{
 private button connectbtn;
 private button sendbtn;
 private textview showview;
 private edittext msgtext;
 private socket socket;
 private handler handler;
 @override
 protected void oncreate(bundle savedinstancestate) {

  super.oncreate(savedinstancestate);

  setcontentview(r.layout.test_network_main);

  connectbtn = (button) findviewbyid(r.id.test_network_main_btn_connect);
  sendbtn = (button) findviewbyid(r.id.test_network_main_btn_send);
  showview = (textview) findviewbyid(r.id.test_network_main_tv_show);
  msgtext = (edittext) findviewbyid(r.id.test_network_main_et_msg);
  connectbtn.setonclicklistener(this);
  sendbtn.setonclicklistener(this);

  handler = new handler(){
   @override
   public void handlemessage(message msg) {
    super.handlemessage(msg);
    string data = msg.getdata().getstring("msg");
    showview.settext("来自服务器的消息:"+data);
   }
  };
 }
 @override
 public void onclick(view v) {
  //连接服务器
  if(v == connectbtn){
   connectserver();
  }
  //发送消息
  if(v == sendbtn){
   string msg = msgtext.gettext().tostring();
   send(msg);
  }
 }
       /**
  *连接服务器的方法
  */
 public void connectserver(){
  try {
   socket = new socket("192.168.1.100",4000);
   system.out.println("连接服务器成功");
   recevie();
  } catch (exception e) {
   system.out.println("连接服务器失败"+e);
   e.printstacktrace();
  }
 }
       /**
  *发送消息的方法
  */
 public void send(string msg){
  try {
   printstream ps = new printstream(socket.getoutputstream());
   ps.println(msg);
   ps.flush();
  } catch (ioexception e) {

   e.printstacktrace();
  }
 }
       /**
  *读取服务器传回的方法
  */
 public void recevie(){

  new thread(){
   public void run(){
    while(true){
     try {
      inputstream is = socket.getinputstream();
      bufferedreader br = new bufferedreader(new inputstreamreader(is));
      string str = br.readline();
      message message = new message();
      bundle bundle = new bundle();
      bundle.putstring("msg", str);
      message.setdata(bundle);
      handler.sendmessage(message);

     } catch (ioexception e) {

      e.printstacktrace();
     }
    }
   }
  }.start();

 }
}


二、rul、urlconnection、httpurlconnection、apachehttp、webview

复制代码 代码如下:

public class testurlactivity extends activity implements onclicklistener {
 private button connectbtn;
 private button urlconnectionbtn;
 private button httpurlconnectionbtn;
 private button httpclientbtn;
 private imageview showimageview;
 private textview showtextview;
 private webview webview;

 @override
 protected void oncreate(bundle savedinstancestate) {

  super.oncreate(savedinstancestate);
  setcontentview(r.layout.test_url_main);

  connectbtn = (button) findviewbyid(r.id.test_url_main_btn_connect);
  urlconnectionbtn = (button) findviewbyid(r.id.test_url_main_btn_urlconnection);
  httpurlconnectionbtn = (button) findviewbyid(r.id.test_url_main_btn_httpurlconnection);
  httpclientbtn = (button) findviewbyid(r.id.test_url_main_btn_httpclient);
  showimageview = (imageview) findviewbyid(r.id.test_url_main_iv_show);
  showtextview = (textview) findviewbyid(r.id.test_url_main_tv_show);
  webview = (webview) findviewbyid(r.id.test_url_main_wv);
  connectbtn.setonclicklistener(this);
  urlconnectionbtn.setonclicklistener(this);
  httpurlconnectionbtn.setonclicklistener(this);
  httpclientbtn.setonclicklistener(this);
 }

 @override
 public void onclick(view v) {
  // 直接使用url对象进行连接
  if (v == connectbtn) {

   try {
    url url = new url("http://192.168.1.100:8080/myweb/image.jpg");
    inputstream is = url.openstream();
    bitmap bitmap = bitmapfactory.decodestream(is);
    showimageview.setimagebitmap(bitmap);
   } catch (exception e) {

    e.printstacktrace();
   }

  }
  // 直接使用urlconnection对象进行连接  
  if (v == urlconnectionbtn) {
   try {

    url url = new url("http://192.168.1.100:8080/myweb/hello.jsp");
    urlconnection connection = url.openconnection();
    inputstream is = connection.getinputstream();
    byte[] bs = new byte[1024];
    int len = 0;
    stringbuffer sb = new stringbuffer();
    while ((len = is.read(bs)) != -1) {
     string str = new string(bs, 0, len);
     sb.append(str);
    }
    showtextview.settext(sb.tostring());
   } catch (exception e) {

    e.printstacktrace();
   }

  }
  // 直接使用httpurlconnection对象进行连接
  if (v == httpurlconnectionbtn) {

   try {
    url url = new url(
      "http://192.168.1.100:8080/myweb/hello.jsp?username=abc");
    httpurlconnection connection = (httpurlconnection) url
      .openconnection();
    connection.setrequestmethod("get");
    if (connection.getresponsecode() == httpurlconnection.http_ok) {
     string message = connection.getresponsemessage();
     showtextview.settext(message);
    }
   } catch (exception e) {

    e.printstacktrace();
   }
  }
  // 使用apachehttp客户端进行连接(重要方法)
  if (v == httpclientbtn) {
   try {

    httpclient client = new defaulthttpclient();
    // 如果是get提交则创建httpget对象,否则创建httppost对象
    // httpget httpget = new
    // httpget("http://192.168.1.100:8080/myweb/hello.jsp?username=abc&pwd=321");
    // post提交的方式
    httppost httppost = new httppost(
      "http://192.168.1.100:8080/myweb/hello.jsp");
    // 如果是post提交可以将参数封装到集合中传递
    list datalist = new arraylist();
    datalist.add(new basicnamevaluepair("username", "aaaaa"));
    datalist.add(new basicnamevaluepair("pwd", "123"));
    // urlencodedformentity用于将集合转换为entity对象
    httppost.setentity(new urlencodedformentity(datalist));
    // 获取相应消息
    httpresponse httpresponse = client.execute(httppost);
    // 获取消息内容
    httpentity entity = httpresponse.getentity();
    // 把消息对象直接转换为字符串
    string content = entityutils.tostring(entity);
                                //showtextview.settext(content);

    //通过webview来解析网页
    webview.loaddatawithbaseurl(null, content, "text/html", "utf-8", null);
    //给点url来进行解析
    //webview.loadurl(url);
   } catch (clientprotocolexception e) {

    e.printstacktrace();
   } catch (ioexception e) {

    e.printstacktrace();
   }
  }
 }

}

三、使用webservice

复制代码 代码如下:

public class loginactivity extends activity implements onclicklistener{
 private button loginbtn;
 private static final string service_url = "http://192.168.1.100:8080/loginservice/loginserviceport";
 private static final string namespace = "http://service.lovo.com/";
 @override
 protected void oncreate(bundle savedinstancestate) {

  super.oncreate(savedinstancestate);
  setcontentview(r.layout.login_main);
  loginbtn = (button) findviewbyid(r.id.login_main_btn_login);
  loginbtn.setonclicklistener(this);
 }
 @override
 public void onclick(view v) {

  if(v == loginbtn){
   //创建webservice的连接对象
   httptransportse httpse = new httptransportse(service_url);
   //通过soap1.1协议对象得到envelop
   soapserializationenvelope envelop = new soapserializationenvelope(soapenvelope.ver11);
   //根据命名空间和方法名来创建soap对象
   soapobject soapobject = new soapobject(namespace, "validate");
   //向调用方法传递参数
   soapobject.addproperty("arg0", "abc");
   soapobject.addproperty("arg1","123");
   //将soapobject对象设置为soapserializationenvelope对象的传出soap消息
   envelop.bodyout = soapobject;
   try {
    //开始调用远程的方法
    httpse.call(null, envelop);
    //得到远程方法返回的soap对象
    soapobject resultobj = (soapobject) envelop.bodyin;
    //根据名为return的键来获取里面的值,这个值就是方法的返回值
    string returnstr = resultobj.getproperty("return").tostring();
    toast.maketext(this, "返回值:"+returnstr, toast.length_long).show();
   } catch (ioexception e) {

    e.printstacktrace();
   } catch (xmlpullparserexception e) {

    e.printstacktrace();
   }

  }

 }
}