বাংলায় অ্যান্ড্রয়েড সহায়িকা - Bangla Android Guide

ডাটা সংযোগ এবং ডাউনলোড

আপনার থ্রেডে আপনার নেটওয়ার্ক লেনদেন করতে, আপনার ডাটা ডাউনলোড বা একটি এঊঞ সম্পাদন করতে আপনি HttpURLConnection ব্যবহার করতে পারেন। Connect()কল করার পর, getInputStream()কল করার মাধ্যমে আপনি ডাটাটির একটি InputStream পেতে পারেন।

নিম্নোক্ত চিত্রটিতে, doInBackground() পদ্ধতিটি পদ্ধতি downloadUrl()কল করে। downloadUrl() পদ্ধতি প্রদত্ত URL গ্রহণ করে এবং HttpURLConnection হয়ে নেটওয়ার্কের সঙ্গে যুক্ত হতে এটা ব্যবহার করে থাকে। যখনই একটি কানেকশন প্রতিষ্ঠিত হয় অ্যাপটি একটি InputStream হিসাবে ডাটা পূণরুদ্ধার করতে পদ্ধতি getInputStream()ব্যবহর করে।

// Given a URL, establishes an HttpUrlConnection and retrieves
// the web page content as a InputStream, which it returns as
// a string.
private String downloadUrl(String myurl) throws IOException {
    InputStream is = null;
    // Only display the first 500 characters of the retrieved
    // web page content.
    int len = 500;

    try {
        URL url = new URL(myurl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        // Starts the query
        conn.connect();
        int response = conn.getResponseCode();
        Log.d(DEBUG_TAG, "The response is: " + response);
        is = conn.getInputStream();

        // Convert the InputStream into a string
        String contentAsString = readIt(is, len);
        return contentAsString;

    // Makes sure that the InputStream is closed after the app is
    // finished using it.
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

উল্লেখ্য যে, পদ্ধতি getResponseCode()কানেকশনের status code ফেরত দেয়। এটা কানেকশন সম্পর্কে অতিরিক্ত তথ্য পেতে এটা একটি কাযকরী পথ। ২০০ এর স্ট্যাটাস কোড সফলতা নির্দেশ করে।