关闭 x
IT技术网
    技 采 号
    ITJS.cn - 技术改变世界
    • 实用工具
    • 菜鸟教程
    IT采购网 中国存储网 科技号 CIO智库

    IT技术网

    IT采购网
    • 首页
    • 行业资讯
    • 系统运维
      • 操作系统
        • Windows
        • Linux
        • Mac OS
      • 数据库
        • MySQL
        • Oracle
        • SQL Server
      • 网站建设
    • 人工智能
    • 半导体芯片
    • 笔记本电脑
    • 智能手机
    • 智能汽车
    • 编程语言
    IT技术网 - ITJS.CN
    首页 » 安卓开发 »Android 三大网络通讯方式详解

    Android 三大网络通讯方式详解

    2015-11-12 00:00:00 出处:codeceo
    分享

    Android平台有三种网络接口可以使用,他们分别是:java.net.*(标准Java接口)、Org.apache接口和Android.net.*(Android网络接口)。下面分别介绍这些接口的功能和作用。

    1.标准Java接口

    java.net.*提供与联网有关的类,包括流、数据包套接字(socket)、Internet协议、常见Http处理等。比如:创建URL,以及URLConnection/HttpURLConnection对象、设置链接参数、链接到服务器、向服务器写数据、从服务器读取数据等通信。这些在Java网络编程中均有涉及,我们看一个简单的socket编程,实现服务器回发客户端信息。

    下面用个例子来说明:

    A、客户端:

    新建Android项目工程:SocketForAndroid(这个随意起名字了吧,我是以这个建立的!)

    下面是main_activity.xml的代码:

    < xml version="1.0" encoding="utf-8" >
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical">
    
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/hello" />
    
        <EditText
            android:id="@+id/message"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/hint" />
    
        <Button
            android:id="@+id/send"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/send" />
    </LinearLayout>

    MainActivity.java的代码入下:

    package com.yaowen.socketforandroid;
    
    import android.os.Bundle;
    
    import android.support.v7.app.AppCompatActivity;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.io.PrintWriter;
    import java.net.Socket;
    
    public class MainActivity extends AppCompatActivity {
        private EditText message;
        private Button send;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            //初始化两个UI控件
            message = (EditText) findViewById(R.id.message);
            send = (Button) findViewById(R.id.send);
            //设置发送按钮的点击事件响应
            send.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Socket socket = null;
                    //获取message输入框里的输入的内容
                    String msg = message.getText().toString() + "/r/n";
                    try {
                        //这里必须是192.168.3.200,不可以是localhost或者127.0.0.1
                        socket = new Socket("192.168.3.200", 18888);
                        PrintWriter out = new PrintWriter(
                                new BufferedWriter(
                                        new OutputStreamWriter(
                                                socket.getOutputStream()
                                        )
                                ), true);
                        //发送消息
                        out.println(msg);
                        //接收数据
                        BufferedReader in = new BufferedReader(
                            new InputStreamReader(
                                socket.getInputStream()
                            )
                        );
                        //读取接收的数据
                        String msg_in = in.readLine();
                        if (null != msg_in) {
                            message.setText(msg_in);
                            System.out.println(msg_in);
                        } else {
                            message.setText("接收的数据有误!");
                        }
                        //关闭各种流
                        out.close();
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            if (null != socket) {
                                //socket不为空时,最后记得要把socket关闭
                                socket.close();
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
        }
    }

    最后别忘记添加访问网络权限:

    <uses-permission android:name="android.permission.INTERNET" />

    B、服务端:

    package service;
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.io.PrintWriter;
    import java.net.ServerSocket;
    import java.net.Socket;
    public class ServerAndroid implements Runnable {
     @Override
     public void run() {
      Socket socket = null;
      try {
       ServerSocket server = new ServerSocket(18888);
       // 循环监听客户端链接请求
       while (true) {
        System.out.println("start...");
        // 接收请求
        socket = server.accept();
        System.out.println("accept...");
        // 接收客户端消息
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String message = in.readLine();
        System.out.println(message);
        // 发送消息,向客户端
        PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),
          true);
        out.println("Server:" + message);
        // 关闭流
        in.close();
        out.close();
       }
      } catch (IOException e) {
       e.printStackTrace();
      } finally {
       if (null != socket) {
        try {
         socket.close();
        } catch (IOException e) {
         e.printStackTrace();
        }
       }
      }
     }
     // 启动服务器
     public static void main(String[] args) {
      Thread server = new Thread(new ServerAndroid());
      server.start();
     }
    }

    C、启动服务器,控制台会打印出“start…”字符串!

    D、运行Android项目文件,如下图:

    Android的三种网络通讯方式详解

    在输入框里输入如下字符串,点发送按钮:

    Android的三种网络通讯方式详解

    服务器收到客户端发来的消息并打印到控制台:

    Android的三种网络通讯方式详解

    2、Apache接口

    对于大部分应用程序而言JDK本身提供的网络功能已远远不够,这时就需要Android提供的Apache HttpClient了。它是一个开源项目,功能更加完善,为客户端的Http编程提供高效、最新、功能丰富的工具包支持。
    下面我们以一个简单例子来看看如何使用HttpClient在Android客户端访问Web。
    首先,要在你的机器上搭建一个web应用test,有两个很简单的PHP文件:hello_get.php和hello_post.php!
    内容如下:

    hello_get.php的代码如下:

    <html>
     <body>
      Welcome < php echo $_GET["name"];  ><br>
      You connected this page on : < php echo $_GET["get"];  >
     </body>
    </html>

    hello_post.php的代码如下:

    <html>
    <body>
    Welcome < php echo $_POST["name"];  ><br>
    You connected this page on : < php echo $_POST["post"];  >
    </body>
    </html>

    在原来的Android项目里新建一个Apache活动类:Apache.java,代码如下:

    package com.yaowen.socketforandroid;
    
    import android.os.Bundle;
    
    import android.support.v7.app.AppCompatActivity;
    import android.view.View;
    import android.widget.Button;
    import android.widget.TextView;
    
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.ClientProtocolException;
    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 java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.UnsupportedEncodingException;
    import java.util.ArrayList;
    import java.util.List;
    
    /**
     * Created by YAOWEN on 2015/11/10.
     */
    public class ApacheActivity extends AppCompatActivity implements View.OnClickListener {
    
        private TextView textView;
        private Button get1, post1;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.apache);
    
            textView = (TextView) findViewById(R.id.textView);
            get1 = (Button) findViewById(R.id.get);
            post1 = (Button) findViewById(R.id.post);
    
            get1.setOnClickListener(this);
            post1.setOnClickListener(this);
    
        }
    
        @Override
        public void onClick(View v) {
            if (v.getId() == R.id.get) {
                //注意:此处ip不能用127.0.0.1或localhost,Android模拟器已将它自己作为了localhost
    
                String url = "http://192.168.3.200/test/hello_get.php name=yaowen&get=GET";
                textView.setText(get(url));
            }
            if (v.getId() == R.id.post) {
    
                String url="http://192.168.3.200/test/hello_post.php";
                textView.setText(post(url));
            }
    
        }
    
        /**
         * 以post方式发送请求,访问web
         *
         * @param url web地址
         * @return 响应数据
         */
        private String post(String url) {
            BufferedReader reader = null;
            StringBuffer sb = null;
            String result = "";
            HttpClient client = new DefaultHttpClient();
            HttpPost requset = new HttpPost(url);
            //保存要传递的参数
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            //添加参数
            params.add(new BasicNameValuePair("name", "yaowen"));
            params.add(new BasicNameValuePair("post","POST"));
    
            try {
                HttpEntity entity = new UrlEncodedFormEntity(params, "utf-8");
                requset.setEntity(entity);
                HttpResponse response = client.execute(requset);
                if (response.getStatusLine().getStatusCode() == 200) {
                    System.out.println("post success");
                    reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                    sb = new StringBuffer();
                    String line = "";
                    String NL = System.getProperty("line.separator");
                    while ((line = reader.readLine()) != null) {
                        sb.append(line);
                    }
                }
    
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (null != reader) {
                    try {
                        reader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
    
                }
                if (null != sb) {
                    result = sb.toString();
                }
            }
    
            return result;
        }
    
        /**
         * 以get方式发送请求,访问web
         *
         * @param url web地址
         * @return 响应数据
         */
        private static String get(String url) {
            BufferedReader bufferedReader = null;
            StringBuffer sb = null;
            String result = "";
            HttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet(url);
            //发送请求,得到响应
            try {
                HttpResponse response = client.execute(request);
                //请求成功
                if (response.getStatusLine().getStatusCode() == 200) {
                    bufferedReader = new BufferedReader(
                            new InputStreamReader(
                                    response.getEntity()
                                            .getContent()
                            )
                    );
                    sb = new StringBuffer();
                    String line = "";
                    String NL = System.getProperty("line.separator");
                    while ((line = bufferedReader.readLine()) != null) {
                        sb.append(line);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (null != bufferedReader) {
                    try {
                        bufferedReader.close();
                        //bufferedReader=null;
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
    
                }
                if (null != sb) {
                    result = sb.toString();
                }
            }
            return result;
        }
    }

    新建一个apache.XML文件,如下:

    < xml version="1.0" encoding="utf-8" >
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical">
    
        <TextView
            android:id="@+id/textView"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="通过按钮选择不同方式访问网页" />
    
        <Button
            android:id="@+id/get"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="get" />
    
        <Button
            android:id="@+id/post"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="post" />
    </LinearLayout>

    结果运行如下:

    Android的三种网络通讯方式详解

    Android的三种网络通讯方式详解

    3.android.net编程

    常常使用此包下的类进行Android特有的网络编程,如:访问WiFi,访问Android联网信息,邮件等功能。

    这里就不详细做例子了,因为这个接触比较多~~~。

    上一篇返回首页 下一篇

    声明: 此文观点不代表本站立场;转载务必保留本文链接;版权疑问请联系我们。

    别人在看

    抖音安全与信任开放日:揭秘推荐算法,告别单一标签依赖

    ultraedit编辑器打开文件时,总是提示是否转换为DOS格式,如何关闭?

    Cornell大神Kleinberg的经典教材《算法设计》是最好入门的算法教材

    从 Microsoft 下载中心安装 Windows 7 SP1 和 Windows Server 2008 R2 SP1 之前要执行的步骤

    Llama 2基于UCloud UK8S的创新应用

    火山引擎DataTester:如何使用A/B测试优化全域营销效果

    腾讯云、移动云继阿里云降价后宣布大幅度降价

    字节跳动数据平台论文被ICDE2023国际顶会收录,将通过火山引擎开放相关成果

    这个话题被围观超10000次,火山引擎VeDI如此解答

    误删库怎么办?火山引擎DataLeap“3招”守护数据安全

    IT头条

    平替CUDA!摩尔线程发布MUSA 4性能分析工具

    00:43

    三起案件揭开侵犯个人信息犯罪的黑灰产业链

    13:59

    百度三年开放2.1万实习岗,全力培育AI领域未来领袖

    00:36

    工信部:一季度,电信业务总量同比增长7.7%,业务收入累计完成4469亿元

    23:42

    Gartner:2024年全球半导体营收6559亿美元,AI助力英伟达首登榜首

    18:04

    技术热点

    iOS 8 中如何集成 Touch ID 功能

    windows7系统中鼠标滑轮键(中键)的快捷应用

    MySQL数据库的23个特别注意的安全事项

    Kruskal 最小生成树算法

    Ubuntu 14.10上安装新的字体图文教程

    Ubuntu14更新后无法进入系统卡在光标界面解怎么办?

      友情链接:
    • IT采购网
    • 科技号
    • 中国存储网
    • 存储网
    • 半导体联盟
    • 医疗软件网
    • 软件中国
    • ITbrand
    • 采购中国
    • CIO智库
    • 考研题库
    • 法务网
    • AI工具网
    • 电子芯片网
    • 安全库
    • 隐私保护
    • 版权申明
    • 联系我们
    IT技术网 版权所有 © 2020-2025,京ICP备14047533号-20,Power by OK设计网

    在上方输入关键词后,回车键 开始搜索。Esc键 取消该搜索窗口。