现在手机大部分功能基本上都依赖网络通讯,Android中的网络通讯支持JDK提供的ServiceScoket,Scoket的TCP/IP通信,支持JDK提供的Datagrampacket,DatagramScoket的UDP通信,当然也支持JDK提供的URL, URLConnection通信,除此之外Android内置了HttpClient,这样可以更加方便的发送Http请求和获取Http的响应。
  对于Android中的TCP/IP和UDP协议通讯,是与Java中的完全相同的,大家可以参考文章《 java中的网络连接 》,在次不再赘述。《 java中的网络连接 》文章的内容比较多,大家可以参照目录查找相关内容(请原谅我当时年轻不会写博客……哈哈)。

  好了,下面进入我们本节的主要内容URLConnection使用……

URLConnection

  在使用URLConnection连接网络之前,我们应该先明白一点:在Android中,耗时的操作是不允许被放在主线程中的,网络连接由于要等待网络的响应,因此是耗时操作,不能放在主线程中。
  
  我们通过一个例子来URLConnection。我们通过一个按钮连接服务器,并将服务器中的信息输出到我们的界面上。我们来看实例实现的整体步骤:
  
1. 定义一个布局文件,布局文件中我们使用到了ScrollView。 由于我们从服务中获得的数据可能比较多,我们的界面可能美版发完整的将数据显示出来,这时我们就是用ScrollView控件,ScrollView控件的使用有一个注意:ScrollView控件中只能定义一个子控件。

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.administrator.networkdemo.UrlConnectionDemo"><LinearLayout  android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent">    <Button  android:id="@+id/button_connect" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="连接网络"/>    <TextView  android:id="@+id/textview_content" android:layout_width="match_parent" android:layout_height="match_parent" /></LinearLayout></ScrollView>

2. Activity中发送连接的请求并或的返回的数据。这儿离我们先贴出整体代码,在分步讲解。

public class UrlConnectionDemo extends Activity implements View.OnClickListener {    //常量    private static final int TYPE_CONNECT = 0x9900;    private Button mButton;    private TextView mTextViewContent;    //开启一个UrlConnnetion的连接    private URLConnection mConnnection;    //创建一个主线程的Handler    private Handler handler = new Handler() {        @Override        public void handleMessage(Message msg) {            super.handleMessage(msg);            switch (msg.what) {                case TYPE_CONNECT:                    String content = (String) msg.obj;                    mTextViewContent.setText(content);                    break;                default:                    break;            }        }    };    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_url_connection_demo);        mButton = (Button) findViewById(R.id.button_connect);        mTextViewContent = (TextView) findViewById(R.id.textview_content);        mButton.setOnClickListener(this);//点击事件    }    @Override    public void onClick(View view) {        switch (view.getId()) {            case R.id.button_connect:                connectServelet();                break;            default:                break;        }    }    private void connectServelet() {        new Thread(new Runnable() {            @Override            public void run() {                try {                    URL url = new URL("http://www.360.com/");//连接的网址                    mConnnection = url.openConnection();//获得连接                    InputStream is = mConnnection.getInputStream();//获得输出流                    //将输出流一顿封装                    BufferedReader br = new BufferedReader(new InputStreamReader(is));                    String line = br.readLine();                    StringBuffer buffer = new StringBuffer();                    while (line != null) {                        Log.d("data", "" + line);                        buffer.append(line);                        line = br.readLine();                    }                    br.close();                    is.close();                    //定义子线程给主线程发送的消息                    Message msg = handler.obtainMessage();                    msg.what = TYPE_CONNECT;                    msg.obj = buffer.toString().trim();                    handler.sendMessage(msg);//发送消息                } catch (MalformedURLException e) {                    e.printStackTrace();                } catch (IOException e) {                    e.printStackTrace();                }            }        }).start();    }}

   在Android中不允许将网络连接耗时操作放在主线程中,我们只能再开一个子线程。但是主线程又不允许子线程修改界面,这是我们就需要使用Handler来实现,不懂得可以先看《 Android中的多线程 》这篇文章了解Handler的使用。这里我么不再具体讲述,只介绍URLConnection部分.
   

  • 创建一个URL对象。URL对象代表统一资源定位器,它指向互联网中的“资源”。也就是我们创建一个指向我们访问地址的“指针”。
  • 通过URL对象获得URLConnectin连接。
  • 通过连接获得输出流对象。
  • 将输出流封装。
    //创建一个指向服务器的地址。    URL url = new URL("http://www.360.com/");    mConnnection =url.openConnection();//获得连接    InputStream is = mConnnection.getInputStream();//获得输出流    //……封装部分省略

结果演示:

更多相关文章

  1. Android中UI主线程与子线程
  2. 如何让android apk 获得系统权限
  3. android使用HttpClient和URLConnection获取网页内容
  4. Android的Handler总结(1)
  5. Android中UI主线程与子线程
  6. Android(安卓)HTTP 实现与服务器通信
  7. Android(安卓)模拟J2me 通过连接框架
  8. Android(安卓)anr介绍
  9. android主线程报ANR的问题!

随机推荐

  1. [android]编译时出现/usr/bin/ld: skippi
  2. 2013.01.03 (2)——— android开发实例之仿
  3. 关于标准android中视频播放器中的快进和
  4. 仿照Android的池化技术
  5. Android Bluetooth Code
  6. 运行时改变Button图片的android:drawable
  7. Android(安卓)AM命令行启动程序的方法
  8. android 状态栏移动到底部
  9. 网络时间同步
  10. Android中启动动画源码讲解