2015-05-17

[Android] 從網路下載資料到字串. Download a String from internet

This is a Util class to download a string from internet.

Usage:
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
String myString = Utils.downloadUrl("http://change.this.to.your.url", connMgr);

Here is the Util Class to download a string from internet:

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

class Utils {

    private static final String DEBUG_TAG = Utils.class.getSimpleName();

    /**
     * Given a URL, establishes an HttpUrlConnection and retrieves
     * the web page content as a InputStream, which it returns as
     * a string
     *
     * @param downloadUrl         download Url
     * @param connectivityManager ConnectivityManager
     *                            from getSystemService(Context.CONNECTIVITY_SERVICE)
     * @return the string downloaded from the downloadUrl
     * @throws IOException
     */
    static String downloadUrl(String downloadUrl,
                              ConnectivityManager connectivityManager) throws IOException {
        if (!isNetworkConnecting(connectivityManager)) {
            return null;
        }

        InputStream is = null;
        String contentAsString = "";

        try {
            URL url = new URL(downloadUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            // Starts the query
            conn.connect();
            int response = conn.getResponseCode();
            Log.d(DEBUG_TAG, "downloadUrl response=" + response);
            if (response == 200) {
                is = conn.getInputStream();
                // Convert the InputStream into a string
                contentAsString = readIt(is);
            }
        } finally {
            if (is != null) {
                is.close();
            }
        }

        return contentAsString;
    }

    // Reads an InputStream and converts it to a String.
    private static String readIt(InputStream stream) {
        BufferedReader reader = null;
        StringBuilder out = new StringBuilder();
        try {
            reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
            String line;
            while ((line = reader.readLine()) != null) {
                out.append(line);
            }
        } catch (IOException ignored) {
            Log.e(DEBUG_TAG, ignored.getMessage(), ignored);
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException ignored) {
                Log.e(DEBUG_TAG, ignored.getMessage(), ignored);
            }
        }
        return out.toString();
    }

    private static boolean isNetworkConnecting(ConnectivityManager connectivityManager) {
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo == null || !networkInfo.isConnected()) {
            Log.d(DEBUG_TAG, "Network is not connected!!");
            return false;
        }
        Log.d(DEBUG_TAG, "Network is connected!!");
        return true;
    }

}