1

i dont know what happen but my code cannot get response / status code and always get blank exception.

if (!GetS1.isEmpty() || !GetS1.equals("")) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    try {
                        url = new URL(GetS1);
                        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                        urlConnection.setConnectTimeout(2000);
                        urlConnection.setReadTimeout(2000);
                        urlConnection.connect();
                        final int responseCode = urlConnection.getResponseCode();
                        if (responseCode == HttpURLConnection.HTTP_OK) {
                            ButtonS1.setEnabled(true);
                            ButtonS1.setText("ACTIVE");
                        } else if (responseCode == HttpURLConnection.HTTP_FORBIDDEN) {
                            ButtonS1.setText("BLOCKED");
                        } else if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) {
                            ButtonS1.setText("DOWN");
                        } else {
                            ButtonS1.setText("UNKNOWN / BROKEN");
                        }
                    } catch (Exception e) {
                        Toast.makeText(Act_Details.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }

am i missing something? i am already set permission using internet in manifest

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Espada
  • 173
  • 1
  • 10
  • Why are you running network operation in UI thread? Network operation is a UI blocking operation you should run this in separate thread and just set results in UI thread. – Niekam Dec 20 '19 at 09:24
  • My code wasn't like this before, but after going around SO someone said that something like this could be done using the `runOnUiThread` method, so I tried to make it like this, and I also tried a number of methods before but it didn't work, always get blank exception or Null exception.. so what should i do now? thanks for fast response. – Espada Dec 20 '19 at 09:34
  • you can use retrofit volley,rx java to get data from network call. – Bunny Dec 20 '19 at 09:38
  • @Bunny I have tried using volley and it works, but for the project that I'm working on right now I want to try the method using HttpURLConnection – Espada Dec 20 '19 at 09:47
  • use asynctask and run the above code in doInBackground method. – Bunny Dec 20 '19 at 09:56

2 Answers2

0

First of all, please post full code, or at least the code of which this above code(which you supplied) is part, Assuming that you are doing this whole job in a separate thead than UI thread, you may do this:

    if (!GetS1.isEmpty() || !GetS1.equals("")) {
        doNetworkCall();
    }

Then make a method:

    private void doNetworkCall(){

    try {
        url = new URL(GetS1);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setConnectTimeout(2000);
        urlConnection.setReadTimeout(2000);
        urlConnection.connect();
        final int responseCode = urlConnection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            ButtonS1.setEnabled(true);
            ButtonS1.setText("ACTIVE");
        } 
        else if (responseCode == HttpURLConnection.HTTP_FORBIDDEN) {
            ButtonS1.setText("BLOCKED");
        }
        else if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) {
            ButtonS1.setText("DOWN");
        } 
        else {
            ButtonS1.setText("UNKNOWN / BROKEN");
            }
        } catch (Exception e) {

        Toast.makeText(Act_Details.this, ""+e,Toast.LENGTH_SHORT).show();
                    }
        }

and check if a toast appears on your screen with some error

dc_1024
  • 31
  • 1
  • 3
  • I've tried this, and I've tried your code too, the result is `android.os.NetworkOnMainThreadException` – Espada Dec 20 '19 at 10:06
  • even I have also tried using a static url `url = new URL(http://google.com);` but the results remain the same, tried with or without http/https. – Espada Dec 20 '19 at 10:10
  • You are getting this error, because you are running in main thread. Try calling in background. Async task could be best for long running task. – yubaraj poudel Dec 20 '19 at 10:13
  • I executed your code but instead of `runOnUiThread` I've passed Runnable to the Thread. Of course you cannot access ui elements, but you can log response to check if endpoint works. – Niekam Dec 20 '19 at 10:28
  • Ofcourse you will get NetworkOnMainThreadException if you call my code in main thread. That is why I am asking for full code. Else do this: Thread thread = new Thread() { @Override public void run() { doNetworkCall(); } }; thread.start(); – dc_1024 Dec 20 '19 at 12:03
0

Finnaly the working code using AsyncTask to check response code..

if (!GetServer1.isEmpty() || !GetServer1.equals("")) {
     new MyTask().execute(GetServer1);
}

private class MyTask extends AsyncTask<String, Integer, String> {

        // Runs in UI before background thread is called
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Do something like display a progress bar

        }

        // This is run in a background thread
        @Override
        protected String doInBackground(String... params) {
            // get the string from params, which is an array
            int StatusCode = 0;
            try {
                String string  = params[0];

                url = new URL(string);
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setConnectTimeout(3000);
                urlConnection.setReadTimeout(3000);
                urlConnection.setRequestMethod("GET");
                urlConnection.setInstanceFollowRedirects(false);
                urlConnection.connect();
                StatusCode = urlConnection.getResponseCode();

            } catch (Exception e) {
                //Toast.makeText(Act_Details.this, ""+e, Toast.LENGTH_SHORT).show();
            }

            return String.valueOf(StatusCode);
        }

        // This is called from background thread but runs in UI
        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            // Do things like update the progress bar

        }

        // This runs in UI when background thread finishes
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            // Do things like hide the progress bar or change a TextView
            ResponseCode = result;

            switch (result) {
                case "200":
                    //Toast.makeText(Act_Details.this, result, Toast.LENGTH_SHORT).show();
                    ButtonS1.setEnabled(true);
                    ButtonS1.setText("ACTIVE");
                    break;
                case "403":
                    ButtonS1.setText("BLOCKED");
                    break;
                case "404":
                    ButtonS1.setText("DOWN");
                    break;
                default:
                    ButtonS1.setText("UNKNOWN / BROKEN");
                    break;
            }

        }
    }

From here

Espada
  • 173
  • 1
  • 10