Tuesday, June 6, 2017

Making HTTP connection in Android

1.You  need to set network security configuration.
    1.1 Add network security config  xml file in project
    1.2 Make above xml file entry in manifest file under <application >  element for attribute android:networkSecurityConfig 
for more details find:
https://developer.android.com/training/articles/security-config.html#manifest

2.add permission to accesses internet in manifest file
<uses-permission android:name="android.permission.INTERNET"></uses-permission> 
3.Never call http connection on main thread it will generate exception  for not_allowed_on_main_thread.
Create separate task handler/ Asynctask/ New background thread and process http connection in it.

Ex:

AsyncTaskRunner runner = new AsyncTaskRunner();
runner.execute();

 private class AsyncTaskRunner extends AsyncTask<String, String, String> 
  {


        @Override        protected String doInBackground(String... params)
        {
            HttpURLConnection urlConnection = null;
            try            {
                URL url = new URL("http://www.android.com/");
                urlConnection = (HttpURLConnection) url.openConnection();
                InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                readStream(in);

                String  str =  in.toString();

                BufferedReader r = new BufferedReader(new InputStreamReader(in));
                StringBuilder total = new StringBuilder();
                String line;
                while ((line = r.readLine()) != null) {
                    total.append(line).append('\n');
                }
                Log.i("",str+ "\n"+total);
            }
            catch (MalformedURLException e)
            {
                e.printStackTrace();
            }
            catch ( IOException e)
            {
                e.printStackTrace();

            }
            catch ( Exception e)
            {
                e.printStackTrace();

            }
            finally            {
                urlConnection.disconnect();
            }

            return resp;
        }


        @Override        protected void onPostExecute(String result) 
        {
           
        }


        @Override        protected void onPreExecute()
        {

        }


        @Override        protected void onProgressUpdate(String... text) 
        {

        }
    }