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

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

概述如今,手机应用渗透到各行各业,数量难以计数,其中大多数应用都会使用到网络,与服务器的交互势不可挡,那么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,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();
   }

  }

 }
}

您可能感兴趣的文章:Android使用URLConnection提交请求的实现Android HttpURLConnection.getResponseCode()错误解决方法Android 中HttpURLConnection与HttpClient使用的简单实例Android中HttpURLConnection与HttpClient的使用与封装Android中使用HttpURLConnection实现GET POST JSON数据与下载图片Android通过HttpURLConnection和HttpClient接口实现网络编程Golang+Android基于HttpURLConnection实现的文件上传功能示例Android开发使用HttpURLConnection进行网络编程详解【附源码下载】Android网络编程之UDP通信模型实例Android开发使用URLConnection进行网络编程详解 总结

以上是内存溢出为你收集整理的android 网络编程之网络通信几种方式实例分享全部内容,希望文章能够帮你解决android 网络编程之网络通信几种方式实例分享所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1142903.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-31
下一篇 2022-05-31

发表评论

登录后才能评论

评论列表(0条)

保存