1

我在多个设备上遇到问题,当设备在一段时间内未与之交互时,我的 HttpUrlConnection 无法按预期运行。项目目标平台为 Android 4.0.3。

下面是我如何使用 HttpUrlConnection 的示例。

new AsyncRequestDTOBaseItemArray(callback).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, url);

实际的 AsyncTask

public class AsyncRequestDTOBaseItem extends AsyncTask<String,String,Object> {

HttpURLConnection connection;
InputStream inStream;
IApiCallback callback;

public AsyncRequestDTOBaseItem(IApiCallback callback) {
    this.callback = callback;
}

@Override
protected Object doInBackground(String... uri) {

    try {
        URL url = new URL(uri[0]);
        connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(5000);
        connection.addRequestProperty("Accept-Encoding", "gzip");
        connection.setInstanceFollowRedirects(false);
        connection.connect();

        String encoding = connection.getContentEncoding();
        // Determine if the stream is compressed and uncompress it if needed.
        if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
            inStream = new GZIPInputStream(connection.getInputStream());
        }  else {
            inStream = connection.getInputStream();
        }

        if (inStream != null) {
           InputStreamReader isr = new InputStreamReader(inStream);
            Gson gson = new Gson();

            try {
                DTOBaseItem item = gson.fromJson(isr, DTOBaseItem.class);
                return item;
            } catch (Exception e) {
                Log.i("AsyncRequestDTOBaseItem", "Exception");
                if (e != null && e.getMessage() != null) {
                    Log.e("AsyncRequestDTOBaseItem", e.getMessage());
                }
            } finally {
                inStream.close();                   
            }
        }   

    } catch (SocketTimeoutException e) {
        Log.i("AsyncRequestDTOBaseItem", "Socket Timeout occured");
    } catch (IOException e) {
        Log.i("AsyncRequestDTOBaseItem","IOException");

        if (e != null && e.getMessage() != null) {
            Log.i("AsyncRequestDTOBaseItem",e.getMessage());
        }

    } finally {
        if (connection != null)
            connection.disconnect();
    }
    return null;
}

@Override
protected void onPostExecute(Object result) {
    callback.Execute(result);
}
}

除非设备处于非活动状态,否则我看不到上述代码有任何问题。当设备处于非活动状态时,最后执行的代码行是

String encoding = connection.getContentEncoding();

我还进入了 wifi 设置并确保我的 wifi 不休眠。起初我以为可能是wifi重新连接造成了这个问题。

4

1 回答 1

0

看起来问题可能是服务器没有发回数据。

我添加了connection.setReadTimeout(5000); 现在问题似乎已经消失了。

于 2013-01-21T00:16:54.230 回答