0

我正在尝试收集一些 json 数据,将它们放在一个字符串中,并通过 toast 在我的应用程序中显示它们以进行测试。我很确定服务器允许我并响应我的请求,因为之前在 Fiddler 上使用相同的 URL(URI)测试了 GET 方法。

这是活动/课程代码:

BufferedReader in = null;
    try {
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet();
        try {
            request.setURI(new URI("http://scards.cloudapp.net/api/AddressBooks/3"));
        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        HttpResponse response = null;
        try {
            response = client.execute(request);
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            in = new BufferedReader
            (new InputStreamReader(response.getEntity().getContent()));
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        StringBuffer sb = new StringBuffer("");
        String line = "";
        String NL = System.getProperty("line.separator");
        try {
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            in.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String page = sb.toString();
        Toast.makeText(this, page, Toast.LENGTH_LONG).show();

        } finally {
        if (in != null) {
            try {
                in.close();
                } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

在 LogCat 中,它显示我有 android.os.NetworkOnMainThreadException。接受建议和更正。

项目属性:SDK:API16 - Android 4.1.2,minBuilSDK:API:7 Android 2.1(Eclair) - Eclipse SDK 4.2

4

2 回答 2

1

下面是一个例子AsyncTask。这里还有一个很棒的教程

class MyAsyncTask extends AsyncTask<String, String, Void> {

    private ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
    InputStream inputStream = null;
    String result = ""; 

    protected void onPreExecute() {
        progressDialog.setMessage("Your progress dialog message...");
        progressDialog.show();
        progressDialog.setOnCancelListener(new OnCancelListener() {
            public void onCancel(DialogInterface arg0) {
                MyAsyncTask.this.cancel(true);
            }
        });
    }

    @Override
    protected Void doInBackground(String... params) {

        String url_select = "http://yoururlhere.com";

                ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();

        try {
            // Set up HTTP post
            // HttpClient is more then less deprecated. Need to change to URLConnection
            HttpClient httpClient = new DefaultHttpClient();

            HttpPost httpPost = new HttpPost(url_select);
            httpPost.setEntity(new UrlEncodedFormEntity(param));
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();

            // Read content & Log
            inputStream = httpEntity.getContent();
        } catch (UnsupportedEncodingException e1) {
            Log.e("UnsupportedEncodingException", e1.toString());
            e1.printStackTrace();
        } catch (ClientProtocolException e2) {
            Log.e("ClientProtocolException", e2.toString());
            e2.printStackTrace();
        } catch (IllegalStateException e3) {
            Log.e("IllegalStateException", e3.toString());
            e3.printStackTrace();
        } catch (IOException e4) {
            Log.e("IOException", e4.toString());
            e4.printStackTrace();
        }
        // Convert response to string using String Builder
        try {
            BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
            StringBuilder sBuilder = new StringBuilder();

            String line = null;
            while ((line = bReader.readLine()) != null) {
                sBuilder.append(line + "\n");
            }

            inputStream.close();
            result = sBuilder.toString();

        } catch (Exception e) {
            Log.e("StringBuilding & BufferedReader", "Error converting result " + e.toString());
        }
    } // protected Void doInBackground(String... params)


    protected void onPostExecute(Void v) {

        //parse JSON data
        try{
            JSONArray jArray = new JSONArray(result);

            for(int i=0; i < jArray.length(); i++) {

                JSONObject jObject = jArray.getJSONObject(i);

                String name = jObject.getString("name");
                String tab1_text = jObject.getString("tab1_text");
                int active = jObject.getInt("active");


            } // End for Loop

            this.progressDialog.dismiss();

        } catch (JSONException e) {

            Log.e("JSONException", "Error: " + e.toString());

        } // catch (JSONException e)


    } // protected void onPostExecute(Void v)

} //class MyAsyncTask extends AsyncTask<String, String, Void>

AsyncTask用这条线打电话给我:

new MyAsyncTask().execute();

这是一个 Youtube 教程(来自新波士顿)AsyncTask,我觉得很有帮助。

Android 应用开发教程 - 101 - Async Task 类加载东西
Android 应用开发教程 - 102 - 4 AsyncTask 方法
Android 应用开发教程 - 103 - ProgressDialog 和修正

于 2012-11-02T14:45:16.997 回答
0

你不应该从主线程访问网络。使用 AsyncTask 类的 doInBackground 方法访问网络。

于 2012-11-02T14:25:40.403 回答