当连接到服务器丢失时,Android应用程序崩溃

时间:2012-02-20 17:01:11

标签: android wcf httpurlconnection

在调试WCF服务时,我遇到了这个问题。我使用HttpURLConnection与服务进行通信。在调试服务时,我遇到了一个问题,我必须在Android应用程序等待响应时停止服务器,导致Android应用程序意外停止。

处理服务器的最佳方法是什么意外突然停止并让Android客户端优雅地处理它。我有请求/ respone通过AsyncTask在后台工作:

@Override
    protected JSONObject doInBackground( BLHttpJSONPostModel ...models) {
        JSONObject jsonObject = null;

        BLHttpJSONPostModel postModel = models[0];
        URL url = null;
        byte[] postData = null;
        String protocol = null;
        String response = null;
        InputStream responseStream = null;
        OutputStream outStream = null;
        HttpURLConnection connection = null;
        BufferedReader bufferedReader = null;
        StringBuilder builder = null;

        try {
            url = new URL( postModel.getUrlString() );
            postData = postModel.getPostDataAsJsonObject().toString().getBytes();
            protocol = url.getProtocol();
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
            return null;
        }

        if ( protocol.equals("https") ) {
            connection = this.setUpHttps( url );    // establishes a secure connection if protocol is HTTPS
        }
        else if ( protocol.equals("http") ) {
            try {
                connection = (HttpURLConnection)url.openConnection();   // establishes un-secured connection
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }
        else
            return null;    // handles unsupported protocol

        try {
            connection.setRequestProperty("Content-Length", String.valueOf(postData.length));
            connection.setRequestProperty("CONTENT-TYPE", "application/json" );
            connection.setRequestMethod( "POST" );
            connection.setUseCaches( false );
            connection.setDoInput( true );
            connection.setDoOutput( true );
            connection.connect();
            outStream = connection.getOutputStream();
            outStream.write(postData);
            outStream.close();

            String _type = connection.getContentType();         // for debugging only
            String _message = connection.getResponseMessage();  // ""
            int size = connection.getContentLength();           // ""

            bufferedReader = new BufferedReader( new InputStreamReader(connection.getInputStream(), "UTF-8") );
            builder = new StringBuilder();

            while( (response = bufferedReader.readLine()) != null ) {
                builder.append(response);
            }
        } catch (IOException e) {
            e.printStackTrace();   // no exceptio caught here
        } finally {
            connection.disconnect();
        }

        if ( (builder != null) && (! builder.toString().equals("")) ) {
            try {
                jsonObject = new JSONObject( builder.toString() );
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        return jsonObject;
    }

堆栈追踪:

02-20 12:13:33.935: E/AndroidRuntime(1173): FATAL EXCEPTION: AsyncTask #1
02-20 12:13:33.935: E/AndroidRuntime(1173): java.lang.RuntimeException: An error occured while executing doInBackground()
02-20 12:13:33.935: E/AndroidRuntime(1173):     at android.os.AsyncTask$3.done(AsyncTask.java:200)
02-20 12:13:33.935: E/AndroidRuntime(1173):     at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
02-20 12:13:33.935: E/AndroidRuntime(1173):     at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
02-20 12:13:33.935: E/AndroidRuntime(1173):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
02-20 12:13:33.935: E/AndroidRuntime(1173):     at java.util.concurrent.FutureTask.run(FutureTask.java:137)
02-20 12:13:33.935: E/AndroidRuntime(1173):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
02-20 12:13:33.935: E/AndroidRuntime(1173):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
02-20 12:13:33.935: E/AndroidRuntime(1173):     at java.lang.Thread.run(Thread.java:1096)
02-20 12:13:33.935: E/AndroidRuntime(1173): Caused by: java.lang.NullPointerException
02-20 12:13:33.935: E/AndroidRuntime(1173):     at java.io.Reader.<init>(Reader.java:65)
02-20 12:13:33.935: E/AndroidRuntime(1173):     at java.io.InputStreamReader.<init>(InputStreamReader.java:93)
02-20 12:13:33.935: E/AndroidRuntime(1173):     at com.beslogic.remotpayment.connection.PostJSONTask.doInBackground(PostJSONTask.java:136)
02-20 12:13:33.935: E/AndroidRuntime(1173):     at com.beslogic.remotpayment.connection.PostJSONTask.doInBackground(PostJSONTask.java:1)
02-20 12:13:33.935: E/AndroidRuntime(1173):     at android.os.AsyncTask$2.call(AsyncTask.java:185)
02-20 12:13:33.935: E/AndroidRuntime(1173):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
02-20 12:13:33.935: E/AndroidRuntime(1173):     ... 4 more

2 个答案:

答案 0 :(得分:1)

我经常遇到这个问题。问题(出于某种原因)是您捕获的Exception对象e可能为null。在try catch语句中,执行以下操作:

try {
    // Network code
} catch(Exception e) {
    if(e != null) {
        e.printStackTrace();
    } else {
        Log.i(appLogTag, "Error: I/O Error");
    }
}

try ... catch块执行此操作。我知道我的解决方案现在听起来很荒谬,但我经常遇到这种情况,认为你可能面临同样的问题。

答案 1 :(得分:1)

答案要简单得多(通常是这样)。

BufferedReader实例化的情况下,由于连接断开,connection.getInputStream()返回null。

应该是:

responseStream = connection.getInputStream();

if ( responseStream != null ) {
    bufferedReader = new BufferedReader( new InputStreamReader(responseStream, "UTF-8") );
    builder = new StringBuilder();

    while( (response = bufferedReader.readLine()) != null ) {
        builder.append(response);
    }
}

这引发了一个未被捕获的运行时异常。