Android網絡訪問的基本方法

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 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,455評論 25 708
  • ¥開啟¥ 【iAPP實現進入界面執行逐一顯】 〖2017-08-25 15:22:14〗 《//首先開一個線程,因...
    小菜c閱讀 6,537評論 0 17
  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,973評論 19 139
  • 《ilua》速成開發手冊3.0 官方用戶交流:iApp開發交流(1) 239547050iApp開發交流(2) 1...
    葉染柒丶閱讀 10,997評論 0 11
  • 晚11,在臺式機打完《全國范圍4G免費WiFi介紹》文檔,關機還沒完畢,就停了電。 得到啟示,不要相信,晚上半夜一...
    小溪終入海閱讀 293評論 1 6