我在多个设备上遇到问题,当设备未与设备进行一段时间的交互时,我的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重新连接造成了这个问题。
答案 0 :(得分:0)
看起来问题可能是服务器没有发回数据。
我添加了 connection.setReadTimeout(5000); ,现在这个问题似乎已经消失了。