0

I want to send this jsonobject finalObject to this server address http://www.xxxx.com/app/pruebaurl I am using this code

     try {

                URL url = new URL("http://www.xxxx.com/app/pruebaurl");

                HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setRequestProperty("Content-Type","application/json");
                httpURLConnection.setRequestProperty("Accept", "application/json");
                httpURLConnection.connect();

                OutputStream outputStream = httpURLConnection.getOutputStream();
                OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, "UTF-8");
                outputStreamWriter.write(finalObject.toString());
                outputStreamWriter.flush();
                outputStreamWriter.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 (Exception e) {
                e.printStackTrace();
      }

but when I run the code by debug I notice that when jumping from line

 httpURLConnection.connect();

to line

OutputStream outputStream = httpURLConnection.getOutputStream();

Generates an error and goes to the exception where it tells me the following

android.os.NetworkOnMainThreadException

I'm working on a fragment, what I can do to fix this error.

gprathour
  • 14,813
  • 5
  • 66
  • 90
jeanf
  • 365
  • 1
  • 3
  • 12

2 Answers2

1

You need to use AsyncTask for performing network operations. You cannot perform it on main thread.

gprathour
  • 14,813
  • 5
  • 66
  • 90
0

In android you are not allowed to do network on your main thread (UI thread). Please use a different thread as mentioned in: How to fix android.os.NetworkOnMainThreadException?

Use AsyncTask or any thread to solve that.

fbwnd
  • 687
  • 6
  • 12