在android中使用REST Web服务

时间:2015-02-13 15:37:23

标签: android rest

我正在尝试使用REST Web服务,该服务返回JSON字典,但是当我调用时应用程序崩溃

HttpResponse resp = httpClient.execute(post);

这是我的代码:

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 

2 个答案:

答案 0 :(得分:1)

基本上,您需要在后台线程中执行网络请求。还有其他多篇SO帖子详细说明了如何做到这一点,例如:

How to fix android.os.NetworkOnMainThreadException?

Android - android.os.NetworkOnMainThreadException

使用处理程序的示例: How to delay execution android

来自android文档的一些信息:NetworkOnMainThreadException

答案 1 :(得分:0)

您无法使用主UI线程来运行Web服务,因此请使用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);
相关问题