Android探索之HttpURLConnection網路請求

總李寫程式碼發表於2016-05-23

前言: 

     最近一直想著學習一下比較好的開源網路框架okhttp,想著學習之前還是先總結一下Android原生提供的網路請求。之前一直在使用HttpClient,但是android 6.0(api 23) SDK,不再提供org.apache.http.*(只保留幾個類).所以我們今天主要總結HttpURLConnection的使用。

HttpURLConnection介紹:

   HttpURLConnection是一種多用途、輕量極的HTTP客戶端,使用它來進行HTTP操作可以適用於大多數的應用程式。對於之前為何一直使用HttpClient而不使用HttpURLConnection也是有原因的。具體分析如下

  • HttpClient是apache的開源框架,封裝了訪問http的請求頭,引數,內容體,響應等等,使用起來比較方便,而HttpURLConnection是java的標準類,什麼都沒封裝,用起來太原始,不方便,比如重訪問的自定義,以及一些高階功能等。
  • 從穩定性方面來說的話,HttpClient很穩定,功能強,BUG少,容易控制細節,而之前的HttpURLConnection一直存在著版本相容的問題,不過在後續的版本中已經相繼修復掉了。

   從上面可以看出之前一直使用HttClient是由於HttpURLConnection不穩定導致,那麼現在谷歌雖然修復了HttpURLConnection之前存在的一些問題之後,相比HttpClient有什麼優勢呢?為何要廢除HttpClient呢?

  • HttpUrlConnection是Android SDK的標準實現,而HttpClient是apache的開源實現;
  • HttpUrlConnection直接支援GZIP壓縮;HttpClient也支援,但要自己寫程式碼處理;
  • HttpUrlConnection直接支援系統級連線池,即開啟的連線不會直接關閉,在一段時間內所有程式可共用;HttpClient當然也能做到,但畢竟不如官方直接系統底層支援好;
  • HttpUrlConnection直接在系統層面做了快取策略處理,加快重複請求的速度。

HttpURLConnection使用:

     Get請求實現:

    private void requestGet(HashMap<String, String> paramsMap) {
        try {
            String baseUrl = "https://xxx.com/getUsers?";
            StringBuilder tempParams = new StringBuilder();
            int pos = 0;
            for (String key : paramsMap.keySet()) {
                if (pos > 0) {
                    tempParams.append("&");
                }
                tempParams.append(String.format("%s=%s", key, URLEncoder.encode(paramsMap.get(key),"utf-8")));
                pos++;
            }
            String requestUrl = baseUrl + tempParams.toString();
            // 新建一個URL物件
            URL url = new URL(requestUrl);
            // 開啟一個HttpURLConnection連線
            HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
            // 設定連線主機超時時間
            urlConn.setConnectTimeout(5 * 1000);
            //設定從主機讀取資料超時
            urlConn.setReadTimeout(5 * 1000);
            // 設定是否使用快取  預設是true
            urlConn.setUseCaches(true);
            // 設定為Post請求
            urlConn.setRequestMethod("GET");
            //urlConn設定請求頭資訊
            //設定請求中的媒體型別資訊。
            urlConn.setRequestProperty("Content-Type", "application/json");
            //設定客戶端與服務連線型別
            urlConn.addRequestProperty("Connection", "Keep-Alive");
            // 開始連線
            urlConn.connect();
            // 判斷請求是否成功
            if (urlConn.getResponseCode() == 200) {
                // 獲取返回的資料
                String result = streamToString(urlConn.getInputStream());
                Log.e(TAG, "Get方式請求成功,result--->" + result);
            } else {
                Log.e(TAG, "Get方式請求失敗");
            }
            // 關閉連線
            urlConn.disconnect();
        } catch (Exception e) {
            Log.e(TAG, e.toString());
        }
    }

    POST請求實現:

    private void requestPost(HashMap<String, String> paramsMap) {
        try {
            String baseUrl = "https://xxx.com/getUsers";
            //合成引數
            StringBuilder tempParams = new StringBuilder();
            int pos = 0;
            for (String key : paramsMap.keySet()) {
                if (pos > 0) {
                    tempParams.append("&");
                }
                tempParams.append(String.format("%s=%s", key,  URLEncoder.encode(paramsMap.get(key),"utf-8")));
                pos++;
            }
            String params =tempParams.toString();
            // 請求的引數轉換為byte陣列
            byte[] postData = params.getBytes();
            // 新建一個URL物件
            URL url = new URL(baseUrl);
            // 開啟一個HttpURLConnection連線
            HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
            // 設定連線超時時間
            urlConn.setConnectTimeout(5 * 1000);
            //設定從主機讀取資料超時
            urlConn.setReadTimeout(5 * 1000);
            // Post請求必須設定允許輸出 預設false
            urlConn.setDoOutput(true);
            //設定請求允許輸入 預設是true
            urlConn.setDoInput(true);
            // Post請求不能使用快取
            urlConn.setUseCaches(false);
            // 設定為Post請求
            urlConn.setRequestMethod("POST");
            //設定本次連線是否自動處理重定向
            urlConn.setInstanceFollowRedirects(true);
            // 配置請求Content-Type
            urlConn.setRequestProperty("Content-Type", "application/json");
            // 開始連線
            urlConn.connect();
            // 傳送請求引數
            DataOutputStream dos = new DataOutputStream(urlConn.getOutputStream());
            dos.write(postData);
            dos.flush();
            dos.close();
            // 判斷請求是否成功
            if (urlConn.getResponseCode() == 200) {
                // 獲取返回的資料
                String result = streamToString(urlConn.getInputStream());
                Log.e(TAG, "Post方式請求成功,result--->" + result);
            } else {
                Log.e(TAG, "Post方式請求失敗");
            }
            // 關閉連線
            urlConn.disconnect();
        } catch (Exception e) {
            Log.e(TAG, e.toString());
        }
    }

處理網路流:將輸入流轉換成字串

    /**
     * 將輸入流轉換成字串
     *
     * @param is 從網路獲取的輸入流
     * @return
     */
    public String streamToString(InputStream is) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = is.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            baos.close();
            is.close();
            byte[] byteArray = baos.toByteArray();
            return new String(byteArray);
        } catch (Exception e) {
            Log.e(TAG, e.toString());
            return null;
        }
    }

   以上就是HttpConnection的get、post的簡單實現,如何實現檔案的下載和上傳呢?

檔案下載:

private void downloadFile(String fileUrl){
        try {
            // 新建一個URL物件
            URL url = new URL(fileUrl);
            // 開啟一個HttpURLConnection連線
            HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
            // 設定連線主機超時時間
            urlConn.setConnectTimeout(5 * 1000);
            //設定從主機讀取資料超時
            urlConn.setReadTimeout(5 * 1000);
            // 設定是否使用快取  預設是true
            urlConn.setUseCaches(true);
            // 設定為Post請求
            urlConn.setRequestMethod("GET");
            //urlConn設定請求頭資訊
            //設定請求中的媒體型別資訊。
            urlConn.setRequestProperty("Content-Type", "application/json");
            //設定客戶端與服務連線型別
            urlConn.addRequestProperty("Connection", "Keep-Alive");
            // 開始連線
            urlConn.connect();
            // 判斷請求是否成功
            if (urlConn.getResponseCode() == 200) {
                String filePath="";
                File  descFile = new File(filePath);
                FileOutputStream fos = new FileOutputStream(descFile);;
                byte[] buffer = new byte[1024];
                int len;
                InputStream inputStream = urlConn.getInputStream();
                while ((len = inputStream.read(buffer)) != -1) {
                    // 寫到本地
                    fos.write(buffer, 0, len);
                }
            } else {
                Log.e(TAG, "檔案下載失敗");
            }
            // 關閉連線
            urlConn.disconnect();
        } catch (Exception e) {
            Log.e(TAG, e.toString());
        }
    }

檔案上傳:

    private void upLoadFile(String filePath, HashMap<String, String> paramsMap) {
        try {
            String baseUrl = "https://xxx.com/uploadFile";
            File file = new File(filePath);
            //新建url物件
            URL url = new URL(baseUrl);
            //通過HttpURLConnection物件,向網路地址傳送請求
            HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
            //設定該連線允許讀取
            urlConn.setDoOutput(true);
            //設定該連線允許寫入
            urlConn.setDoInput(true);
            //設定不能適用快取
            urlConn.setUseCaches(false);
            //設定連線超時時間
            urlConn.setConnectTimeout(5 * 1000);   //設定連線超時時間
            //設定讀取超時時間
            urlConn.setReadTimeout(5 * 1000);   //讀取超時
            //設定連線方法post
            urlConn.setRequestMethod("POST");
            //設定維持長連線
            urlConn.setRequestProperty("connection", "Keep-Alive");
            //設定檔案字符集
            urlConn.setRequestProperty("Accept-Charset", "UTF-8");
            //設定檔案型別
            urlConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + "*****");
            String name = file.getName();
            DataOutputStream requestStream = new DataOutputStream(urlConn.getOutputStream());
            requestStream.writeBytes("--" + "*****" + "\r\n");
            //傳送檔案引數資訊
            StringBuilder tempParams = new StringBuilder();
            tempParams.append("Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" + name + "\"; ");
            int pos = 0;
            int size=paramsMap.size();
            for (String key : paramsMap.keySet()) {
                tempParams.append( String.format("%s=\"%s\"", key, paramsMap.get(key), "utf-8"));
                if (pos < size-1) {
                    tempParams.append("; ");
                }
                pos++;
            }
            tempParams.append("\r\n");
            tempParams.append("Content-Type: application/octet-stream\r\n");
            tempParams.append("\r\n");
            String params = tempParams.toString();
            requestStream.writeBytes(params);
            //傳送檔案資料
            FileInputStream fileInput = new FileInputStream(file);
            int bytesRead;
            byte[] buffer = new byte[1024];
            DataInputStream in = new DataInputStream(new FileInputStream(file));
            while ((bytesRead = in.read(buffer)) != -1) {
                requestStream.write(buffer, 0, bytesRead);
            }
            requestStream.writeBytes("\r\n");
            requestStream.flush();
            requestStream.writeBytes("--" + "*****" + "--" + "\r\n");
            requestStream.flush();
            fileInput.close();
            int statusCode = urlConn.getResponseCode();
            if (statusCode == 200) {
                // 獲取返回的資料
                String result = streamToString(urlConn.getInputStream());
                Log.e(TAG, "上傳成功,result--->" + result);
            } else {
                Log.e(TAG, "上傳失敗");
            }
        } catch (IOException e) {
            Log.e(TAG, e.toString());
        }
    }

 

許可權:

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

 

知識擴充套件:

  • 關於ResponseCode(http://univasity.iteye.com/blog/963433)

  • 關於 Content-Type(http://blog.csdn.net/blueheart20/article/details/45174399)

 

相關文章