1. 程式人生 > >Android之使用HttpURLConnection進行網路訪問

Android之使用HttpURLConnection進行網路訪問

一、概述

在Android 上傳送HTTP 請求的方式一般有兩種:HttpURLConnection 和HttpClient。因為在Android 5.0之後,HttpClient被HttpURLConnecetion替代,後來在Android 6.0完全被捨棄,所以本文重點講解HttpURLConnecetion。

二、HttpURLConnecetion的使用步驟

(1)首先需要獲取到HttpURLConnection 的例項,一般只需new 出一個URL 物件,並傳入目標的網路地址,然後呼叫一下openConnection()方法即可,如下所示:

URL url = new URL("http://www.baidu.com"
); HttpURLConnection connection = (HttpURLConnection) url.openConnection();

(2)得到了HttpURLConnection 的例項之後,我們可以設定一下HTTP 請求所使用的方法。常用的方法主要有兩個,GET 和POST。GET 表示希望從伺服器那裡獲取資料,而POST 則表示希望提交資料給伺服器。寫法如下:

httpURLConnection.setRequestMethod("GET");

(3)接下來就可以進行一些自由的定製了,比如設定連線超時、讀取超時的毫秒數,以及伺服器希望得到的一些訊息頭等。這部分內容根據自己的實際情況進行編寫,示例寫法如下:

connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);

(4)之後再呼叫getInputStream()方法就可以獲取到伺服器返回的輸入流了,剩下的任務就是對輸入流進行讀取,如下所示:

InputStream in = connection.getInputStream();

(5)最後可以呼叫disconnect()方法將這個HTTP 連線關閉掉,如下所示:

connection.disconnect();

三、HttpURLConnecetion的使用範例

為簡單起見,還是在Android之AsyncTask詳解

基礎上修改,實現下載圖片的功能,原本使用HttpClient實現,我們換做HttpURLConnecetion來實現。

package com.wz;

import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    private ProgressDialog progressDialog;//下載進度條
    private Button button;
    private ImageView imageView;

    //圖片下載地址
    private final String IMAGE_URL = "http://a.hiphotos.baidu.com/image/pic/item/fcfaaf51f3deb48fc4cedcdff21f3a292df5780f.jpg";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new MyAsyncTask().execute(IMAGE_URL);
            }
        });
        imageView = (ImageView) findViewById(R.id.imageView);

        progressDialog = new ProgressDialog(this);
        progressDialog.setTitle("提示");
        progressDialog.setMessage("正在下載,請稍後...");
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

    }

    class MyAsyncTask extends AsyncTask<String, Integer, Bitmap> {
        @Override
        protected void onPreExecute() {
            // 顯示進度對話方塊
            progressDialog.show();
        }

        @Override
        protected Bitmap doInBackground(String... params) {
            Bitmap bitmap = null;
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            InputStream inputStream = null;
            HttpURLConnection connection = null;
            try {
                //第一步,獲取到HttpURLConnection 的例項
                URL url = new URL(params[0]);
                connection = (HttpURLConnection) url.openConnection();
                //第二步,設定一下HTTP 請求所使用的方法GET ,從伺服器那裡獲取資料
                connection.setRequestMethod("GET");
                //第三步,設定連線超時、讀取超時
                connection.setConnectTimeout(8000);
                connection.setConnectTimeout(8000);
                int code = connection.getResponseCode();
                if (code == 200) {
                    //第四步,獲取到伺服器返回的輸入流,並進行讀取
                    inputStream = connection.getInputStream();
                    long file_len = connection.getContentLength();
                    int len = 0;
                    byte[] data = new byte[1024];
                    int total_len = 0;
                    while ((len = inputStream.read(data)) != -1) {
                        total_len += len;
                        int value = (int) ((total_len / (float) file_len) * 100);
                        //反饋當前任務的執行進度
                        publishProgress(value);
                        outputStream.write(data, 0, len);
                    }
                    byte[] result = outputStream.toByteArray();
                    bitmap = BitmapFactory.decodeByteArray(result, 0, result.length);
                }

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                //第五步,將這個HTTP 連線關閉掉
                if(connection != null){
                    connection.disconnect();
                }
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return bitmap;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            //設定進度條刻度
            progressDialog.setProgress(values[0]);
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            //關閉進度條
            progressDialog.dismiss();
            //顯示圖片
            imageView.setImageBitmap(bitmap);
        }
    }
}