-1

I'm tyring to consume a REST Web Service which returns a JSON Dictionary but the app crashes when I call

HttpResponse resp = httpClient.execute(post);

This is my code:

System.out.println("onClick!!!");
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost post = new HttpPost("http://applocalize.com.br/rest/rest.php");
        post.setHeader("content-type", "application/json; charset=UTF-8");
        post.setHeader("Accept", "application/json");
        //Construimos el objeto cliente en formato JSON
        JSONObject dato = new JSONObject();

        try {
            dato.put("pg","categorias");
            dato.put("serv", "buscar");
            dato.put("dt_atualizacao", "");

            StringEntity entity = new StringEntity(dato.toString());
            post.setEntity(entity);

            HttpResponse resp = httpClient.execute(post);
            String respStr = EntityUtils.toString(resp.getEntity());


            System.out.println("OKAY!");

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

LOGCAT:

 28517-28517/com.allapps.localizeapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.allapps.localizeapp/com.allapps.localizeapp.MapsActivity}: android.os.NetworkOnMainThreadException
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2252)
            at 
Marcus
  • 6,697
  • 11
  • 46
  • 89
CodeHunter
  • 11
  • 8

2 Answers2

1

Basically, you need to execute your network request in a background thread. There are multiple other SO posts that outline exactly how to do that, such as:

How to fix android.os.NetworkOnMainThreadException?

Android - android.os.NetworkOnMainThreadException

Example using handlers: How to delay execution android

And a little info from the android docs: NetworkOnMainThreadException

Community
  • 1
  • 1
invertigo
  • 6,336
  • 5
  • 39
  • 64
0

You can not use main UI thread to run web service, so do it with Ansynctask:

new AsyncTask<Void, Void, String>() {
        @Override
        protected String doInBackground(Void... params) {

            //put your web service here

            return result;
        }

        @Override
        protected void onPostExecute(String result) {

            //here do something with main UI thread
        }
    }.execute(null, null, null);
Xcihnegn
  • 11,579
  • 10
  • 33
  • 33