美文网首页
Android网络访问的基本方法

Android网络访问的基本方法

作者: flemingchen | 来源:发表于2016-07-26 22:57 被阅读727次

    Android访问网络的两种主要方式:
    1、标准Java接口(java.net) ----HttpURLConnection,可以实现简单的基于URL请求、响应功能;
    2、Apache接口(org.appache.http)----HttpClient,使用起来更方面更强大。一般来说,用这种接口。

    下面以一个安卓项目为例分别介绍这两个类的用法:
    该项目的主要功能是访问百度www.baidu.com网址,将返回的html内容显示在安卓界面上。
    1、新建布局文件

    <RelativeLayout 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"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        tools:context=".MainActivity">
        <Button
            android:id="@+id/click"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="click" />
        <ScrollView
            android:layout_below="@+id/click"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <TextView
                android:id="@+id/hello"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/hello_world" />
        </ScrollView>
    </RelativeLayout>
    

    这里用到了按钮和文字,由于安卓界面大小的原因,我将文字部分放置在ScrollView(滚动视图)中,以便用户查看内容。

    2、MainActivity.java

    /*在Android上发送HTTP请求的方式一般有两种,HttpURLConnection和HttpClient,现在先学习下
        HttpURLConnection的用法。
        1、获取HttpURLConnection的实例,new 出一个URL对象,并传入目标网络的地址    调用一下openConnection()方法即可,如下所示:
       URL URL = new URL("http://www.baidu.com");
       HttpURLConnection connection = (HttpURLConnection)url.openConnection();
       2、设置一下HTTP请求所使用的方法。常用的方法主要有两个,
        (1)GET表示希望从服务器那里获取数据。
        (2)POST则表示提交数据给服务器。写法如下:
         connection.setRequestMethod("GET");
       3、接下来就可以进行一些自由的定制了,比如设置连接超时,读取超时的毫秒数,以及服务器希望得到的一些消息头等。
        这部分内容根据自己的实际情况进行编写,示例如下:
          connection.setConnectionTimeout(8000);
          connection.setReadTimeout(8000);
       4、调用getInputStream()方法就可以获取到服务器返回的输入流了
        ,剩下的任务就是对输入流进行读取,如下所示:
          InputStream in = connection.getInputStream();
       5、最后可以调用disconnect()方法将这个HTTP连接关闭掉,如下所示:                       
          connection.disconnection();*/
    

    完整代码:

    package com.chen.networktest;
    import android.os.Handler;
    import android.os.Message;
    import android.support.v7.app.ActionBarActivity;
    import android.os.Bundle;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.widget.Button;
    import android.widget.TextView;
    import java.io.BufferedReader;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.URL;
    public class MainActivity extends ActionBarActivity {
        public static final int SHOW_RESPONSE = 0;
        private Button buttonClick;
        private TextView textViewResult;    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            buttonClick = (Button) findViewById(R.id.click);
            textViewResult = (TextView) findViewById(R.id.hello);
    
            buttonClick.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    sendRequestWithHttpURLConnection();
                }
            });
        }
        //实例化Handler对象,用于在子线程发送消息到主线程,并在主线程进行消息处理
        private Handler handler = new Handler() {
            //handleMessage方法运行在主线程,处理子线程发送回来的数据。
            @Override
            public void handleMessage(Message msg) {
                // TODO Auto-generated method stub
                super.handleMessage(msg);
                switch (msg.what) {
                    case SHOW_RESPONSE:
                        String response = (String) msg.obj;
                        //在这里进行UI操作,将结果显示到界面上
                        textViewResult.setText(response);
                        break;
                    default:
                        break;
                }
            }
        };
        private void sendRequestWithHttpURLConnection() {
            //开启线程来发起网络请求
            new Thread(new Runnable() {
                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    HttpURLConnection connection = null;
                    try {
                        URL url = new URL("http://www.baidu.com");
                        connection = (HttpURLConnection) url.openConnection();
                        connection.setRequestMethod("GET");
                        connection.setConnectTimeout(5000);
                        connection.setReadTimeout(5000);
                        InputStream in = connection.getInputStream();
                        //下面对获取到的输入流进行读取
                        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                        StringBuilder response = new StringBuilder();
                        String line;
                        while ((line = reader.readLine()) != null) {
                            response.append(line);
                        }
                        //实例化Message对象
                        Message message = new Message();
                        message.what = SHOW_RESPONSE;
                        //将服务器返回的结果存放到Message中
                        message.obj = response.toString();
                        //sendMessage方法运行在子线程
                        handler.sendMessage(message);
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        if (connection != null) {
                            connection.disconnect();
                        }
                    }
                }
            }).start();
        }
    }
    

    HttpClient的用法:
    1、获取HttpClient的实例,new DefaultHttpClient()这个实现类
    2、实例化HttpGet或者HttpPost对象,参数为一个url

    private void sendRequestWithHttpClient() {
       new Thread(new Runnable() {
           @Override
           public void run() {
               // TODO Auto-generated method stub
               try {
                   HttpClient httpClient = new DefaultHttpClient();
                   HttpGet httpGet = new HttpGet("http://www.baidu.com");
                   HttpResponse httpResponse = httpClient.execute(httpGet);
                   if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                       //请求和响应都成功了
                       HttpEntity entity = httpResponse.getEntity();
                       String response = EntityUtils.toString(entity, "utf-8");
                       Message message = new Message();
                       message.what = SHOW_RESPONSE;
                       //将服务器返回的结果存放到Message中
                       message.obj = response.toString();
                       handler.sendMessage(message);
                   }
               } catch (Exception e) {
                   e.printStackTrace();
               }
           }
       }).start();
    }
    

    注意:记得在AndroidManifest.xml里面添加权限

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

    相关文章

      网友评论

          本文标题:Android网络访问的基本方法

          本文链接:https://www.haomeiwen.com/subject/vdqojttx.html