urlconnection error on Android: NetworkOnMainThreadException

1

I'm trying to use url connection in my android app and it gives me the following error:

  

FATAL EXCEPTION: main                                                                    android.os.NetworkOnMainThreadException                                                                        at   android.os.StrictMode $ AndroidBlockGuardPolicy.onNetwork (StrictMode.java:1128)                                                                        at java.net.InetAddress.lookupHostByName (InetAddress.java:385)                                                                        at java.net.InetAddress.getAllByNameImpl (InetAddress.java:236)                                                                        at java.net.InetAddress.getAllByName (InetAddress.java:214)                                                                        at libcore.net.http.HttpConnection. (HttpConnection.java:70)                                                                        at libcore.net.http.HttpConnection. (HttpConnection.java:50)                                                                        at   libcore.net.http.HttpConnection $ Address.connect (HttpConnection.java:340)                                                                        at libcore.net.http.HttpConnectionPool.get (HttpConnectionPool.java:87)                                                                        at libcore.net.http.HttpConnection.connect (HttpConnection.java:128)                                                                        at   libcore.net.http.HttpEngine.openSocketConnection (HttpEngine.java:316)                                                                        at libcore.net.http.HttpEngine.connect (HttpEngine.java:311)                                                                        at libcore.net.http.HttpEngine.sendSocketRequest (HttpEngine.java:290)                                                                        at libcore.net.http.HttpEngine.sendRequest (HttpEngine.java:240)                                                                        at   libcore.net.http.HttpURLConnectionImpl.connect (HttpURLConnectionImpl.java:81)                                                                        at Nuevo6.makeRequest (New6.java:86)                                                                        at New6 $ 1.onClick (New6.java:64)                                                                        at android.view.View.performClick (View.java:4421)                                                                        at android.view.View $ PerformClick.run (View.java:18190)                                                                        at android.os.Handler.handleCallback (Handler.java:725)                                                                        at android.os.Handler.dispatchMessage (Handler.java:92)                                                                        at android.os.Looper.loop (Looper.java:175)                                                                        at android.app.ActivityThread.main (ActivityThread.java:5279)                                                                        at java.lang.reflect.Method.invokeNative (Native Method)                                                                        at java.lang.reflect.Method.invoke (Method.java:511)                                                                        at   com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run (ZygoteInit.java:1102)                                                                        at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:869)                                                                        at dalvik.system.NativeStart.main (Native Method)

I leave the onCreate () code

ImageView siguiente = (ImageView) findViewById(R.id.imageView2);
        siguiente.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Log.i("Vehiculos",vehiculos.getText().toString());

                miCC.setVehiclos(vehiculos.getText().toString());
                miCC.setAparcamiento(apar.getText().toString());
                miCC.setInfo(notas.getText().toString());

                Gson gson = new Gson();
                json = gson.toJson(miCC);

                Log.i("JSON",json);

                String result = makeRequest("urlWebService",json);

                Intent passIntent = new Intent();
                passIntent.setClass(Nuevo6.this,Menu.class);
                startActivity(passIntent);
            }
        });

As I see in the log, the JSON encoding is correct and the url of the webService works well, because if I put it in the browser, it inserts a new record with the empty data in the DB.

And finally I leave you the makeRequest function that is the one that gives the problem in the statement: " urlConnection.connect();"

 public static String makeRequest(String uri, String json) {
        HttpURLConnection urlConnection;
        String url;
        String data = json;
        String result = null;
        try
        {
            urlConnection = (HttpURLConnection) ((new URL(uri).openConnection()));
            urlConnection.setDoOutput(true);
            urlConnection.setRequestProperty("Content-Type", "application/json");
            urlConnection.setRequestProperty("Accept", "application/json");
            urlConnection.setRequestMethod("POST");
            urlConnection.connect();

            OutputStream outputStream = urlConnection.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            writer.write(data);
            writer.close();
            outputStream.close();

            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
            String line = null; StringBuilder sb = new StringBuilder();
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line);
            }
            bufferedReader.close();
            result = sb.toString();
        }
        catch (UnsupportedEncodingException e) {
            e.printStackTrace(); }
        catch (IOException e) {
            e.printStackTrace(); }
        return result;
    }

I think my error should be a bit higher in the urlConnection = (HttpURLConnection) ((new URL(uri).openConnection())); statement since I'm not using the string url variable, but I've put the url as uri ( link ) and I do not know if you have to do a casting or what, I think uri and url is not the same and I'm having a bad time with the show.

Thank you very much, best regards

    
asked by midlab 20.11.2018 в 17:53
source

2 answers

0

There were two problems, on the one hand I was putting a String instead of a URL variable and on the other I had to add the sentence:

if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy =
                    new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

I'll leave you with the makeRequest function in case you can / want to reuse it:

public static String makeRequest(String json) {
        HttpURLConnection urlConnection;
        URL url;

        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy =
                    new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

        try {
            url = new URL("http://www.miWebService.php");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        String data = json;
        String result = null;
        try
        {
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setDoOutput(true);
            urlConnection.setRequestProperty("Content-Type", "application/json");
            urlConnection.setRequestProperty("Accept", "application/json");
            urlConnection.setRequestMethod("POST");
            urlConnection.connect();

            OutputStream outputStream = urlConnection.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            writer.write(data);
            writer.close();
            outputStream.close();

            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
            String line = null; StringBuilder sb = new StringBuilder();
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line);
            }
            bufferedReader.close();
            result = sb.toString();
        }
        catch (UnsupportedEncodingException e) {
            e.printStackTrace(); }
        catch (IOException e) {
            e.printStackTrace(); }
        return result;
    }

Already if you want to be a bit more "PRO" put it in an AsyncTask so that in case of failure the main thread is not blocked and you can show a Toast that the communication with the server failed !!!

    
answered by 20.11.2018 в 19:36
0

According to your LogCat the problem is NetworkOnMainThreadException

  

NetworkOnMainThreadException : Caused when you try to perform   operations on the main thread (Main thread), which is incorrect.

Error android.os. NetworkOnMainThreadException in using Android HttpURLConnection

To solve this as an option, make your request within a Asynctask .

How to get the value of an AsyncTask? Wait until you get the result

public class RequestTask extends AsyncTask <String,String,String> {

    @Override
    public String doInBackground(String... params) {

        String uri= params[0];
        String json = params[1];
        /*--------------------------------------------*/
        HttpURLConnection urlConnection;
        String url;
        String data = json;
        String result = null;
        try
        {
            urlConnection = (HttpURLConnection) ((new URL(uri).openConnection()));
            urlConnection.setDoOutput(true);
            urlConnection.setRequestProperty("Content-Type", "application/json");
            urlConnection.setRequestProperty("Accept", "application/json");
            urlConnection.setRequestMethod("POST");
            urlConnection.connect();

            OutputStream outputStream = urlConnection.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            writer.write(data);
            writer.close();
            outputStream.close();

            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
            String line = null; StringBuilder sb = new StringBuilder();
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line);
            }
            bufferedReader.close();
            result = sb.toString();
        }
        catch (UnsupportedEncodingException e) {
            e.printStackTrace(); }
        catch (IOException e) {
            e.printStackTrace(); }
        return result;
        /*--------------------------------------------*/

    }

    @Override
    protected void onPreExecute() {
    }

    @Override
    public void onPostExecute(String result) {
        //result retorna valor obtenido por la petición.
    }

    @Override
    protected void onProgressUpdate(String... values) {
    }
}

to obtain the result of the request must be done in this way:

  //String result = makeRequest("urlWebService",json);
  String resultadoPeticion =  new RequestTask().execute(new String[]{"urlWebService",json}).get();

P.D. Do not use this in a production application :

StrictMode.ThreadPolicy policy =
                    new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);

what it does is deactivate the policy of not allowing operations on the main thread.

    
answered by 20.11.2018 в 19:08