Getting Exception at HttpConnection.connect() android

2.2k views Asked by At

Getting Excception at httpConn.connect(); (the 5th last line of the code) Code and Exeption Errors are given below..I an trying to connect the android application to internet..I got this code from internet..but it is giving exception..The code is completely given bewlow..i have added permission to manifest already i dont know what is te erroe

Code..

 public class httpsData extends Activity {

    ImageView img;

  @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String str = DownloadText("http://www.edumobile.org/android/");
        TextView txt = (TextView) findViewById(R.id.text);
        txt.setText(str);        
    }   

    private String DownloadText(String URL)
    { Log.v("Wasim ","11");
        int BUFFER_SIZE = 2000;
        InputStream in = null;
        try {
            in = OpenHttpConnection(URL);
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            return "";
        }
        InputStreamReader isr = new InputStreamReader(in);
        int charRead;
        String str = "";
        char[] inputBuffer = new char[BUFFER_SIZE];          
        try {
            while ((charRead = isr.read(inputBuffer))>0)
            {                    
                //---convert the chars to a String---
                String readString = String.copyValueOf(inputBuffer, 0, charRead);
                str += readString;
                inputBuffer = new char[BUFFER_SIZE];
            }
            in.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "";
        }    
        return str;        
    }

    private InputStream OpenHttpConnection(String urlString) 
    throws IOException
    {
        InputStream in = null;
        int response = -1;

        URL url = new URL(urlString); 

        URLConnection conn = url.openConnection();     
       if (!(conn instanceof HttpURLConnection))  
        {
            throw new IOException("Not an HTTP connection");
        }

            HttpURLConnection httpConn = (HttpURLConnection) conn;
            httpConn.setAllowUserInteraction(false);
            httpConn.setInstanceFollowRedirects(true);
            httpConn.setRequestMethod("GET");
            httpConn.connect();
            response = httpConn.getResponseCode();                 
            if (response == HttpURLConnection.HTTP_OK) {
                in = httpConn.getInputStream();                                 
    }   
             return in;     
    }
}

Error are these:

    12-04 14:57:34.947: E/AndroidRuntime(5851): FATAL EXCEPTION: main
    12-04 14:57:34.947: E/AndroidRuntime(5851): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.apps.httpsData/com.apps.httpsData.httpsData}: android.os.NetworkOnMainThreadException
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at android.app.ActivityThread.access$600(ActivityThread.java:130)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at android.os.Handler.dispatchMessage(Handler.java:99)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at android.os.Looper.loop(Looper.java:137)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at android.app.ActivityThread.main(ActivityThread.java:4745)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at java.lang.reflect.Method.invokeNative(Native Method)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at java.lang.reflect.Method.invoke(Method.java:511)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at dalvik.system.NativeStart.main(Native Method)
    12-04 14:57:34.947: E/AndroidRuntime(5851): Caused by: android.os.NetworkOnMainThreadException
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at java.net.InetAddress.getAllByName(InetAddress.java:214)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:341)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:315)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at libcore.net.http.HttpEngine.connect(HttpEngine.java:310)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:289)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:239)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:80)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at com.apps.httpsData.httpsData.OpenHttpConnection(httpsData.java:97)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at com.apps.httpsData.httpsData.DownloadText(httpsData.java:42)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at com.apps.httpsData.httpsData.onCreate(httpsData.java:30)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at android.app.Activity.performCreate(Activity.java:5008)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     ... 11 more
3

There are 3 answers

2
Hariharan On BEST ANSWER

Try this..

TextView txt;

 @Override 
 public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    txt = (TextView) findViewById(R.id.text);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
        new DownloadText("http://www.edumobile.org/android/").executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new String[]{null});
    else
        new DownloadText("http://www.edumobile.org/android/").execute(new String[]{null});

}

    public class DownloadText extends AsyncTask<String, Void, String> {

        // variables passed in:
        String urls;
        //  constructor
        public DownloadText(String urls) {
            this.urls = urls;
        }

        @Override
        protected void onPreExecute() {
            pDialog = ProgressDialog.show(httpsData.this, "Fetching Details..", "Please wait...", true);
        }


        @Override
        protected String doInBackground(String... params) {
            // TODO Auto-generated method stub


             int BUFFER_SIZE = 2000;
        InputStream in = null;
        try {

        InputStream in = null;
        int response = -1;

        URL url = new URL(urls); 

        URLConnection conn = url.openConnection();     
       if (!(conn instanceof HttpURLConnection))  
        {
            throw new IOException("Not an HTTP connection");
        }

            HttpURLConnection httpConn = (HttpURLConnection) conn;
            httpConn.setAllowUserInteraction(false);
            httpConn.setInstanceFollowRedirects(true);
            httpConn.setRequestMethod("GET");
            httpConn.connect();
            response = httpConn.getResponseCode();                 
            if (response == HttpURLConnection.HTTP_OK) {
                in = httpConn.getInputStream();                                 
    } 

        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            return "";
        }
        InputStreamReader isr = new InputStreamReader(in);
        int charRead;
        String str = "";
        char[] inputBuffer = new char[BUFFER_SIZE];          
        try {
            while ((charRead = isr.read(inputBuffer))>0)
            {                    
                //---convert the chars to a String---
                String readString = String.copyValueOf(inputBuffer, 0, charRead);
                str += readString;
                inputBuffer = new char[BUFFER_SIZE];
            }
            in.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "";
        } 
        }

        @Override
        protected void onPostExecute(String result) {
            // Now we have your JSONObject, play around with it.
            if (pDialog.isShowing())
                pDialog.dismiss();

            if(!result.equals(""))
                txt.setText(result);
        }

    }
0
Divya Motiwala On

You cannot execute HTTP connect request on main thread.

Use an Async Task and perform http request in doInBackground() method.

1
nitesh On

you have to use asynch task for this purpose. To execute Server class use these code in your method from where you want to call HTTP CONNECTION----------- Server downloadFile = new Server(); downloadFile.execute();

class Server extends AsyncTask<String, Integer, String> {

    @Override
    protected String doInBackground(String... arg0) {
        // TODO Auto-generated method stub
        try{
            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
             HttpClient httpclient = new DefaultHttpClient();
             //link
             String adad="http://"+iP+"/"+faCility+"/distt.php";
             HttpPost httppost = new HttpPost(adad);

             nameValuePairs.add(new BasicNameValuePair(uSername,pAssword));
             httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));


              response = httpclient.execute(httppost);
              if(response !=null)
              {

                  HttpEntity entityy = response.getEntity();
                     is = entityy.getContent();

              }


             }catch(Exception e){
                 Log.e("log_tag", "Error in http connection"+e.toString());

            }
        //convert response to string
        if(is !=null){
        try{//StringBuilder sb = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);


              System.out.println("66666666666666");
                   //todo your work here with "is"


              sb = new StringBuilder();
               sb.append(reader.readLine() + "\n");

               System.out.println("77777777777");
               String line="0";
               while ((line = reader.readLine()) != null) {
                             sb.append(line + "\n");

               }

               is.close();
                System.out.println("88888888888888");
              System.out.println(sb);
                result=sb.toString();
    System.out.println("---------------------------------"+result+"---------------------");
                System.out.println("9999999999999999999");
                       }catch(Exception e){
                      Log.e("log_tag", "Error converting result "+e.toString());

                }
        }

        return result;
    }
    protected void onPostExecute(String resultt)
    {
    }
    }