Day 7 : Making A Get Request in Android

2 min read

Dear Friends

 

images_m

 

Lets play with Networking in Android.

Important rule :

Every network transaction  should only be done on a worker thread. 

I think above line is worth repeating Every network transaction  should only be done on a worker thread. 

Now the question is why ?

Fetching data from network is a long running operation that could block your UI Thread if you try to make network calls on UI Thread. Thus increasing user frustration and sluggishness of your app. Also some of functionalities might break in between.

There is an array of problems those may result in network transaction is done on UI Thread. So like a good OS android , in newer version android doesn’t allow developers to make network call on UI Thread.

Here we are making a Get request to fetch some data from Network using a worker thread.

  public class FetchDataUserTask extends AsyncTask<Void, Integer, Boolean> {


        StringBuffer responseString = new StringBuffer("");
        int mConnectionCode;
        HashMap<String, String> hmVars;


        public FetchDataUserTask(HashMap<String, String> hm) {
            this.hmVars = hm;
        }


        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }

        @Override
        protected Boolean doInBackground(Void... params) {
            try {

                String server = "relsellglobal.in";
                String port = "80";
                String urlToHit = "http://" + server + ":" + port + "/DeliveryS/CRKInsightsServer/mobilecheck.php";
                String urlData = getUrlStringData(hmVars);

                if (urlData.substring(urlData.length() - 1).equalsIgnoreCase("&")) {
                    urlData = urlData.substring(0, (urlData.length() - 1));
                }
                urlToHit +="?"+urlData;

                URL url = new URL(urlToHit);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");

                connection.setDoInput(true);



                mConnectionCode = connection.getResponseCode();

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                if (mConnectionCode == HttpURLConnection.HTTP_OK) {

                    InputStream inputStream = connection.getInputStream();
                    BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));

                    String line = "";

                    while ((line = rd.readLine()) != null) {
                        responseString.append(line);
                    }

                    return true;
                }
            } catch (IOException e) {
                Log.v("Message", e.getMessage());
                e.printStackTrace();
                return false;

            }
            return false;
        }

        @Override
        protected void onPostExecute(Boolean success) {

            if (success) {
                System.out.println("Response String "+responseString);

            




                } else if (mConnectionCode >= HttpURLConnection.HTTP_BAD_REQUEST && mConnectionCode < HttpURLConnection.HTTP_INTERNAL_ERROR) {


                } else if (mConnectionCode >= HttpURLConnection.HTTP_MULT_CHOICE && mConnectionCode < HttpURLConnection.HTTP_BAD_REQUEST) {


                }
            }
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);


        }
    }

    public String getUrlStringDataStr(HashMap<String, String> map) {
        String result = "";

        Set<String> myset = map.keySet();
        int setSize = myset != null ? myset.size() : 0;
        int i = 0;

        for (String key : myset) {
            String value = map.get(key);
            result += key + "=" + value;
            if (i <= setSize - 1)
                result += "&";
            i++;
        }
        return result;
    }

    public String getUrlStringData(HashMap<String, String> incomingHm) throws UnsupportedEncodingException {

        String result = "";

        Set<String> keys = incomingHm.keySet();
        HashMap<String, String> map = new HashMap<String, String>();
        for (String key : keys) {
            map.put(key, URLEncoder.encode(incomingHm.get(key), "UTF-8"));
        }
        result = getUrlStringDataStr(map);

        System.out.println(result);

        return result;
    }

 

So what we have to do.

Create an activity and then use worker thread instance to execute GET Request.

So somewhere in onCreate of your activity

 

HashMap<String, String> map = new HashMap<>();
map.put("controlVar","50");
map.put("full_name","relsell global");
new FetchDataUserTask(map).execute().

 

Inside below method

 

 protected void onPostExecute(Boolean success) {

            if (success) {
                System.out.println("Response String "+responseString);

           
                } else if (mConnectionCode >= HttpURLConnection.HTTP_BAD_REQUEST && mConnectionCode < HttpURLConnection.HTTP_INTERNAL_ERROR) {


                } else if (mConnectionCode >= HttpURLConnection.HTTP_MULT_CHOICE && mConnectionCode < HttpURLConnection.HTTP_BAD_REQUEST) {


                }
            }
        }

we get response from server. Response String will be having null, empty , success response.

Few important points

  1. To make network calls in android, application should have Network permission.
<uses-permission android:name="android.permission.INTERNET"/>

 

2. onPostExecute method is execute in UI thread. so there is not need of handler mechanism here to communicate with UI thread.

 

 

Homework : At last but not the least , create an android application that can fetch an image from network and show it in UI.

 

 

 

 

Happy Coding.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *