Search code examples
androidjsonandroid-studiohttpwebrequestwebrequest

Android Studio: Get a connection to a URL


I am having a little bit of trouble getting JSON to load in my project.

I used this getJSON method listed in the answers but it won't work. I figured out that simply the connect() function is throwing a RuntimeException.

Here is my whole class including the getJSON method from another question:

private class GetUnis extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... params) {
        HttpsURLConnection con = null;
        try {
            URL u = new URL(URL2);
            con = (HttpsURLConnection) u.openConnection();

            con.connect();


            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }
            br.close();

            test = sb.toString();


        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (con != null) {
                try {
                    con.disconnect();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
        return null;
    }
}

And I am calling it like this: new GetUnis().execute();

Edit: Here is the StackTrace

java.lang.RuntimeException: An error occured while executing doInBackground()
                                                                                   at android.os.AsyncTask$3.done(AsyncTask.java:304)
                                                                                   at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
                                                                                   at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
                                                                                   at java.util.concurrent.FutureTask.run(FutureTask.java:242)
                                                                                   at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
                                                                                   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
                                                                                   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
                                                                                   at java.lang.Thread.run(Thread.java:818)
                                                                                Caused by: java.lang.ClassCastException: com.android.okhttp.internal.http.HttpURLConnectionImpl cannot be cast to javax.net.ssl.HttpsURLConnection
                                                                                   at com.example.lukaskohl.myapplication.SelectUni$GetUnis.doInBackground(SelectUni.java:138)
                                                                                   at com.example.lukaskohl.myapplication.SelectUni$GetUnis.doInBackground(SelectUni.java:131)
                                                                                   at android.os.AsyncTask$2.call(AsyncTask.java:292)
                                                                                   at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                                   at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 
                                                                                   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 
                                                                                   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 
                                                                                   at java.lang.Thread.run(Thread.java:818) 

 


Solution

  • You can call it from you ui thread you need to do this in a background thread

    Basically create an asynctask and move your logic to connect to there

    use this code to get the json response as string:

    /**
         * This method returns the entire result from the HTTP response.
         *
         * @param url The URL to fetch the HTTP response from.
         * @return The contents of the HTTP response.
         * @throws IOException Related to network and stream reading
         */
        public static String getResponseFromHttpUrl(URL url) throws IOException {
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            try {
                InputStream in = urlConnection.getInputStream();
    
                Scanner scanner = new Scanner(in);
                scanner.useDelimiter("\\A");
    
                boolean hasInput = scanner.hasNext();
                if (hasInput) {
                    return scanner.next();
                } else {
                    return null;
                }
            } finally {
                urlConnection.disconnect();
            }
        }
    

    this one is to check internet connection and will help you avoid calling this task when the user is offline

      public static boolean isNetworkAvaliable(Context ctx) {
            ConnectivityManager connectivityManager = (ConnectivityManager) ctx
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
           return  ((connectivityManager
                    .getNetworkInfo(ConnectivityManager.TYPE_MOBILE) != null && connectivityManager
                    .getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED)
                    || (connectivityManager
                    .getNetworkInfo(ConnectivityManager.TYPE_WIFI) != null && connectivityManager
                    .getNetworkInfo(ConnectivityManager.TYPE_WIFI)
                    .getState() == NetworkInfo.State.CONNECTED)) ;
        }
    
    
    
    
    
    
    
    
        private class GetUnits extends AsyncTask<URL, Void, String> {
    
    
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
    
            }
    
            @Override
            protected String doInBackground(URL... params) {
                URL Url = params[0];
    
                String searchResults = null;
                try {
                    searchResults =getResponseFromHttpUrl(Url);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if(searchResults!=null){
                    try {
                        JSONArray unitsArray = new  JSONArray(searchResults);
                        // do something cool with units
    //// TODO: 02/08/2017  
                    }catch (Exception e){
                        e.printStackTrace();
                        Log.e("Places","error "+e);
                    }
    
                return searchResults;
            }
    
            @Override
            protected void onPostExecute(String searchResults) {
    
    
    
            }
        }