zl程序教程

您现在的位置是:首页 >  移动开发

当前栏目

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

Android实例网络编程 方式 分享 几种 网络通信
2023-06-13 09:15:14 时间

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

现在总结了六种方式:


(1)针对TCP/IP的Socket、ServerSocket

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

(3)针对直接URL的HttpURLConnection。

(4)Google集成了ApacheHTTP客户端,可使用HTTP进行网络编程。

(5)使用WebService。Android可以通过开源包如jackson去支持Xmlrpc和Jsonrpc,另外也可以用Ksoap2去实现Webservice。

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

一、socket与serverSocket

客户端代码

复制代码代码如下:


publicclassTestNetworkActivityextendsActivityimplementsOnClickListener{
 privateButtonconnectBtn;
 privateButtonsendBtn;
 privateTextViewshowView;
 privateEditTextmsgText;
 privateSocketsocket;
 privateHandlerhandler;
 @Override
 protectedvoidonCreate(BundlesavedInstanceState){

  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=newHandler(){
   @Override
   publicvoidhandleMessage(Messagemsg){
    super.handleMessage(msg);
    Stringdata=msg.getData().getString("msg");
    showView.setText("来自服务器的消息:"+data);
   }
  };
 }
 @Override
 publicvoidonClick(Viewv){
  //连接服务器
  if(v==connectBtn){
   connectServer();
  }
  //发送消息
  if(v==sendBtn){
   Stringmsg=msgText.getText().toString();
   send(msg);
  }
 }
      /**
 *连接服务器的方法
 */
 publicvoidconnectServer(){
  try{
   socket=newSocket("192.168.1.100",4000);
   System.out.println("连接服务器成功");
   recevie();
  }catch(Exceptione){
   System.out.println("连接服务器失败"+e);
   e.printStackTrace();
  }
 }
      /**
 *发送消息的方法
 */
 publicvoidsend(Stringmsg){
  try{
   PrintStreamps=newPrintStream(socket.getOutputStream());
   ps.println(msg);
   ps.flush();
  }catch(IOExceptione){

   e.printStackTrace();
  }
 }
      /**
 *读取服务器传回的方法
 */
 publicvoidrecevie(){

  newThread(){
   publicvoidrun(){
    while(true){
     try{
      InputStreamis=socket.getInputStream();
      BufferedReaderbr=newBufferedReader(newInputStreamReader(is));
      Stringstr=br.readLine();
      Messagemessage=newMessage();
      Bundlebundle=newBundle();
      bundle.putString("msg",str);
      message.setData(bundle);
      handler.sendMessage(message);

     }catch(IOExceptione){

      e.printStackTrace();
     }
    }
   }
  }.start();

 }
}


二、RUL、URLConnection、httpURLConnection、ApacheHttp、WebView

复制代码代码如下:

publicclassTestURLActivityextendsActivityimplementsOnClickListener{
 privateButtonconnectBtn;
 privateButtonurlConnectionBtn;
 privateButtonhttpUrlConnectionBtn;
 privateButtonhttpClientBtn;
 privateImageViewshowImageView;
 privateTextViewshowTextView;
 privateWebViewwebView;

 @Override
 protectedvoidonCreate(BundlesavedInstanceState){

  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
 publicvoidonClick(Viewv){
  //直接使用URL对象进行连接
  if(v==connectBtn){

   try{
    URLurl=newURL("http://192.168.1.100:8080/myweb/image.jpg");
    InputStreamis=url.openStream();
    Bitmapbitmap=BitmapFactory.decodeStream(is);
    showImageView.setImageBitmap(bitmap);
   }catch(Exceptione){

    e.printStackTrace();
   }

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

    URLurl=newURL("http://192.168.1.100:8080/myweb/hello.jsp");
    URLConnectionconnection=url.openConnection();
    InputStreamis=connection.getInputStream();
    byte[]bs=newbyte[1024];
    intlen=0;
    StringBuffersb=newStringBuffer();
    while((len=is.read(bs))!=-1){
     Stringstr=newString(bs,0,len);
     sb.append(str);
    }
    showTextView.setText(sb.toString());
   }catch(Exceptione){

    e.printStackTrace();
   }

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

   try{
    URLurl=newURL(
      "http://192.168.1.100:8080/myweb/hello.jsp?username=abc");
    HttpURLConnectionconnection=(HttpURLConnection)url
      .openConnection();
    connection.setRequestMethod("GET");
    if(connection.getResponseCode()==HttpURLConnection.HTTP_OK){
     Stringmessage=connection.getResponseMessage();
     showTextView.setText(message);
    }
   }catch(Exceptione){

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

    HttpClientclient=newDefaultHttpClient();
    //如果是Get提交则创建HttpGet对象,否则创建HttpPost对象
    //HttpGethttpGet=new
    //HttpGet("http://192.168.1.100:8080/myweb/hello.jsp?username=abc&pwd=321");
    //post提交的方式
    HttpPosthttpPost=newHttpPost(
      "http://192.168.1.100:8080/myweb/hello.jsp");
    //如果是Post提交可以将参数封装到集合中传递
    ListdataList=newArrayList();
    dataList.add(newBasicNameValuePair("username","aaaaa"));
    dataList.add(newBasicNameValuePair("pwd","123"));
    //UrlEncodedFormEntity用于将集合转换为Entity对象
    httpPost.setEntity(newUrlEncodedFormEntity(dataList));
    //获取相应消息
    HttpResponsehttpResponse=client.execute(httpPost);
    //获取消息内容
    HttpEntityentity=httpResponse.getEntity();
    //把消息对象直接转换为字符串
    Stringcontent=EntityUtils.toString(entity);
                               //showTextView.setText(content);

    //通过webview来解析网页
    webView.loadDataWithBaseURL(null,content,"text/html","utf-8",null);
    //给点url来进行解析
    //webView.loadUrl(url);
   }catch(ClientProtocolExceptione){

    e.printStackTrace();
   }catch(IOExceptione){

    e.printStackTrace();
   }
  }
 }

}

三、使用webService

复制代码代码如下:
publicclassLoginActivityextendsActivityimplementsOnClickListener{
 privateButtonloginBtn;
 privatestaticfinalStringSERVICE_URL="http://192.168.1.100:8080/loginservice/LoginServicePort";
 privatestaticfinalStringNAMESPACE="http://service.lovo.com/";
 @Override
 protectedvoidonCreate(BundlesavedInstanceState){

  super.onCreate(savedInstanceState);
  setContentView(R.layout.login_main);
  loginBtn=(Button)findViewById(R.id.login_main_btn_login);
  loginBtn.setOnClickListener(this);
 }
 @Override
 publicvoidonClick(Viewv){

  if(v==loginBtn){
   //创建WebService的连接对象
   HttpTransportSEhttpSE=newHttpTransportSE(SERVICE_URL);
   //通过SOAP1.1协议对象得到envelop
   SoapSerializationEnvelopeenvelop=newSoapSerializationEnvelope(SoapEnvelope.VER11);
   //根据命名空间和方法名来创建SOAP对象
   SoapObjectsoapObject=newSoapObject(NAMESPACE,"validate");
   //向调用方法传递参数
   soapObject.addProperty("arg0","abc");
   soapObject.addProperty("arg1","123");
   //将SoapObject对象设置为SoapSerializationEnvelope对象的传出SOAP消息
   envelop.bodyOut=soapObject;
   try{
    //开始调用远程的方法
    httpSE.call(null,envelop);
    //得到远程方法返回的SOAP对象
    SoapObjectresultObj=(SoapObject)envelop.bodyIn;
    //根据名为return的键来获取里面的值,这个值就是方法的返回值
    StringreturnStr=resultObj.getProperty("return").toString();
    Toast.makeText(this,"返回值:"+returnStr,Toast.LENGTH_LONG).show();
   }catch(IOExceptione){

    e.printStackTrace();
   }catch(XmlPullParserExceptione){

    e.printStackTrace();
   }

  }

 }
}