处理Android中的网络错误

时间:2014-02-19 23:12:06

标签: android json parsing networking connection

我有一个可以连接到互联网的小应用程序,但我无法弄清楚如何处理超时和没有连接错误。我有一个简单的JSONParser接受请求,我已经尝试捕获HttpHostConnectionException但无济于事。我如何添加超时限制和吐司让用户知道连接不好,如果无法连接(Android当前有哪些),我如何避免我的应用程序关闭?

我的JSONParser

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params) throws HttpHostConnectException {

        // Making HTTP request
        try {

            // check for request method
            if(method.equalsIgnoreCase("POST")){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            }else if(method.equalsIgnoreCase("GET")){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            }           


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

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
            Log.d("JSON Parser", json.toString());
        }

        // return JSON String
        return jObj;

    }
}

使用示例

protected String doInBackground(String... args) {

    try {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        // getting JSON string from URL
        JSONObject json = jParser.makeHttpRequest(url_all_orders, "GET", params);

        // Checking for SUCCESS TAG
        int success = json.getInt(TAG_SUCCESS);

        if (success == 1) {
            // orders found
            // Getting Array of Orders
            orders = json.getJSONArray(TAG_ORDERS);

            // looping through All Orders
            for (int i = 0; i < orders.length(); i++) {
                JSONObject c = orders.getJSONObject(i);

                // Storing each json item in variable
                String id = c.getString(TAG_OID);
                String name = c.getString(TAG_NAME);

                // creating new HashMap
                HashMap<String, String> map = new HashMap<String, String>();

                // adding each child node to HashMap key => value
                map.put(TAG_OID, id);
                map.put(TAG_NAME, name);

                // adding HashList to ArrayList
                ordersList.add(map);
            }
        } else {
            // no orders found
            // Launch Add New product Activity
            Intent i = new Intent(getApplicationContext(),
                    CreateOrderActivity.class);
            // Closing all previous activities
            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(i);
        }
    } catch (JSONException e) {
        pDialog.dismiss();
        e.printStackTrace();
    } catch (HttpHostConnectException e){
        Toast.makeText(getApplicationContext(), "Error getting connection", Toast.LENGTH_LONG).show();
        pDialog.dismiss();
        e.printStackTrace();
    }

    return null;
}

相关错误消息

02-19 14:34:30.033: W/System.err(22424): org.apache.http.conn.HttpHostConnectException: Connection to http://192.168.1.42 refused
02-19 14:34:30.053: W/System.err(22424):    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:183)
02-19 14:34:30.053: W/System.err(22424):    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
02-19 14:34:30.083: W/System.err(22424):    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
02-19 14:34:30.083: W/System.err(22424):    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
02-19 14:34:30.083: W/System.err(22424):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
02-19 14:34:30.093: W/System.err(22424):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
02-19 14:34:30.093: W/System.err(22424):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
02-19 14:34:30.093: W/System.err(22424):    at com.cbs.iomamobile.JSONParser.makeHttpRequest(JSONParser.java:63)
02-19 14:34:30.093: W/System.err(22424):    at com.cbs.iomamobile.AllOrdersActivity$LoadAllOrders.doInBackground(AllOrdersActivity.java:148)
02-19 14:34:30.093: W/System.err(22424):    at com.cbs.iomamobile.AllOrdersActivity$LoadAllOrders.doInBackground(AllOrdersActivity.java:1)
02-19 14:34:30.093: W/System.err(22424):    at android.os.AsyncTask$2.call(AsyncTask.java:264)
02-19 14:34:30.093: W/System.err(22424):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
02-19 14:34:30.093: W/System.err(22424):    at java.util.concurrent.FutureTask.run(FutureTask.java:137)
02-19 14:34:30.093: W/System.err(22424):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
02-19 14:34:30.093: W/System.err(22424):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
02-19 14:34:30.093: W/System.err(22424):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
02-19 14:34:30.093: W/System.err(22424):    at java.lang.Thread.run(Thread.java:856)
02-19 14:34:30.093: W/System.err(22424): Caused by: java.net.ConnectException: failed to connect to /192.168.1.42 (port 80): connect failed: ETIMEDOUT (Connection timed out)
02-19 14:34:30.103: W/System.err(22424):    at libcore.io.IoBridge.connect(IoBridge.java:114)
02-19 14:34:30.113: W/System.err(22424):    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
02-19 14:34:30.113: W/System.err(22424):    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
02-19 14:34:30.113: W/System.err(22424):    at java.net.Socket.connect(Socket.java:842)
02-19 14:34:30.113: W/System.err(22424):    at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
02-19 14:34:30.113: W/System.err(22424):    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
02-19 14:34:30.113: W/System.err(22424):    ... 16 more
02-19 14:34:30.113: W/System.err(22424): Caused by: libcore.io.ErrnoException: connect failed: ETIMEDOUT (Connection timed out)
02-19 14:34:30.123: W/System.err(22424):    at libcore.io.Posix.connect(Native Method)
02-19 14:34:30.123: W/System.err(22424):    at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:85)
02-19 14:34:30.123: W/System.err(22424):    at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
02-19 14:34:30.123: W/System.err(22424):    at libcore.io.IoBridge.connect(IoBridge.java:112)
02-19 14:34:30.123: W/System.err(22424):    ... 21 more
02-19 14:34:30.123: E/Buffer Error(22424): Error converting result java.lang.NullPointerException
02-19 14:34:30.133: E/JSON Parser(22424): Error parsing data org.json.JSONException: End of input at character 0 of 
02-19 14:34:30.153: W/dalvikvm(22424): threadid=12: thread exiting with uncaught exception (group=0x409ee1f8)
02-19 14:34:30.163: E/AndroidRuntime(22424): FATAL EXCEPTION: AsyncTask #1
02-19 14:34:30.163: E/AndroidRuntime(22424): java.lang.RuntimeException: An error occured while executing doInBackground()
02-19 14:34:30.163: E/AndroidRuntime(22424):    at android.os.AsyncTask$3.done(AsyncTask.java:278)
02-19 14:34:30.163: E/AndroidRuntime(22424):    at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
02-19 14:34:30.163: E/AndroidRuntime(22424):    at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
02-19 14:34:30.163: E/AndroidRuntime(22424):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
02-19 14:34:30.163: E/AndroidRuntime(22424):    at java.util.concurrent.FutureTask.run(FutureTask.java:137)
02-19 14:34:30.163: E/AndroidRuntime(22424):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
02-19 14:34:30.163: E/AndroidRuntime(22424):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
02-19 14:34:30.163: E/AndroidRuntime(22424):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
02-19 14:34:30.163: E/AndroidRuntime(22424):    at java.lang.Thread.run(Thread.java:856)
02-19 14:34:30.163: E/AndroidRuntime(22424): Caused by: java.lang.NullPointerException
02-19 14:34:30.163: E/AndroidRuntime(22424):    at com.cbs.iomamobile.AllOrdersActivity$LoadAllOrders.doInBackground(AllOrdersActivity.java:151)
02-19 14:34:30.163: E/AndroidRuntime(22424):    at com.cbs.iomamobile.AllOrdersActivity$LoadAllOrders.doInBackground(AllOrdersActivity.java:1)
02-19 14:34:30.163: E/AndroidRuntime(22424):    at android.os.AsyncTask$2.call(AsyncTask.java:264)
02-19 14:34:30.163: E/AndroidRuntime(22424):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
02-19 14:34:30.163: E/AndroidRuntime(22424):    ... 5 more
02-19 14:34:30.313: D/OpenGLRenderer(22424): Flushing caches (mode 0)
02-19 14:34:30.353: D/OpenGLRenderer(22424): Flushing caches (mode 0)
02-19 14:34:30.543: E/WindowManager(22424): Activity com.cbs.iomamobile.AllOrdersActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@410a2608 that was originally added here
02-19 14:34:30.543: E/WindowManager(22424): android.view.WindowLeaked: Activity com.cbs.iomamobile.AllOrdersActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@410a2608 that was originally added here
02-19 14:34:30.543: E/WindowManager(22424):     at android.view.ViewRootImpl.<init>(ViewRootImpl.java:357)
02-19 14:34:30.543: E/WindowManager(22424):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:267)
02-19 14:34:30.543: E/WindowManager(22424):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:215)
02-19 14:34:30.543: E/WindowManager(22424):     at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:140)
02-19 14:34:30.543: E/WindowManager(22424):     at android.view.Window$LocalWindowManager.addView(Window.java:537)
02-19 14:34:30.543: E/WindowManager(22424):     at android.app.Dialog.show(Dialog.java:285)
02-19 14:34:30.543: E/WindowManager(22424):     at com.cbs.iomamobile.AllOrdersActivity$LoadAllOrders.onPreExecute(AllOrdersActivity.java:132)
02-19 14:34:30.543: E/WindowManager(22424):     at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:561)
02-19 14:34:30.543: E/WindowManager(22424):     at android.os.AsyncTask.execute(AsyncTask.java:511)
02-19 14:34:30.543: E/WindowManager(22424):     at com.cbs.iomamobile.AllOrdersActivity.onCreate(AllOrdersActivity.java:72)
02-19 14:34:30.543: E/WindowManager(22424):     at android.app.Activity.performCreate(Activity.java:4492)
02-19 14:34:30.543: E/WindowManager(22424):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
02-19 14:34:30.543: E/WindowManager(22424):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
02-19 14:34:30.543: E/WindowManager(22424):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
02-19 14:34:30.543: E/WindowManager(22424):     at android.app.ActivityThread.access$600(ActivityThread.java:123)
02-19 14:34:30.543: E/WindowManager(22424):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
02-19 14:34:30.543: E/WindowManager(22424):     at android.os.Handler.dispatchMessage(Handler.java:99)
02-19 14:34:30.543: E/WindowManager(22424):     at android.os.Looper.loop(Looper.java:137)
02-19 14:34:30.543: E/WindowManager(22424):     at android.app.ActivityThread.main(ActivityThread.java:4424)
02-19 14:34:30.543: E/WindowManager(22424):     at java.lang.reflect.Method.invokeNative(Native Method)
02-19 14:34:30.543: E/WindowManager(22424):     at java.lang.reflect.Method.invoke(Method.java:511)
02-19 14:34:30.543: E/WindowManager(22424):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
02-19 14:34:30.543: E/WindowManager(22424):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
02-19 14:34:30.543: E/WindowManager(22424):     at dalvik.system.NativeStart.main(Native Method)

0 个答案:

没有答案