Artificial Intelligence Programming Lab(AIPLab) 討論區

Please login or register.

請輸入帳號, 密碼以及預計登入時間

新聞:

[慶賀]恭喜張清貿醫師升任北榮傳醫科主治醫師-20170201

作者 主題: [物件] HttpURLConnection  (閱讀 791 次)

admin

  • 管理員
  • Hero Member
  • *****
  • 文章: 1748
    • 檢視個人資料
[物件] HttpURLConnection
« 於: 九月 24, 2014, 01:19:50 am »
(1) AndroidManifest.xml
程式碼: [Select]
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
(2) Check  networkInfo.isConnected
程式碼: [Select]
TextView tv = (TextView) findViewById(R.id.textView1);
       
        ConnectivityManager connMgr = (ConnectivityManager)
                getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
        tv.setText("Enter UrlConnect");
        new DownloadTask().execute("http://clinic.aiplab.net/visit_now.php");
        }
        else{
        tv.setText("No Network Connect");
        }
(3)  AsyncTask<String, Void, String>
程式碼: [Select]
private class DownloadTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... urls) {
       
            try {
                return loadFromNetwork(urls[0]);
            } catch (IOException e) {
               return getString(R.string.connection_error);
            }
        //return "XXXX";
        }

        /**
         * Uses the logging framework to display the output of the fetch
         * operation in the log fragment.
         */
        @Override
        protected void onPostExecute(String result) {
            Log.i(TAG, result);
            TextView tv = (TextView) findViewById(R.id.textView1);
        tv.setText(result);
        }
    }

    /** Initiates the fetch operation. */
    private String loadFromNetwork(String urlString) throws IOException {
        InputStream stream = null;
        String str ="NONO";

        try {
            stream = downloadUrl(urlString);
            str = readIt(stream, 500);
       } finally {
           if (stream != null) {
               stream.close();
            }
        }
        return str;
    }

    /**
     * Given a string representation of a URL, sets up a connection and gets
     * an input stream.
     * @param urlString A string representation of a URL.
     * @return An InputStream retrieved from a successful HttpURLConnection.
     * @throws java.io.IOException
     */
    private InputStream downloadUrl(String urlString) throws IOException {
        // BEGIN_INCLUDE(get_inputstream)
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        // Start the query
        conn.connect();
        //InputStream stream =null;
        InputStream stream = conn.getInputStream();
        return stream;
        // END_INCLUDE(get_inputstream)
    }

    /** Reads an InputStream and converts it to a String.
     * @param stream InputStream containing HTML from targeted site.
     * @param len Length of string that this method returns.
     * @return String concatenated according to len parameter.
     * @throws java.io.IOException
     * @throws java.io.UnsupportedEncodingException
     */
    private String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
        Reader reader = null;
        reader = new InputStreamReader(stream, "UTF-8");
        char[] buffer = new char[len];
        reader.read(buffer);
        return new String(buffer);
    }
已記錄
 

SimplePortal Classic 2.0.5