我正在开发我的第一个应用程序,并且我创建了以下连接到远程URL的方法,获取JSON文件并将其写入本地SQLite数据库。有时会发生互联网连接缓慢或不良,我会设置一个计时器。例如,如果3秒后它不会得到JSON文件,我会抛出AlertDialog让用户选择是否重试或取消。那么如何给我的函数添加超时?如何在Android中添加HttpClient请求和连接超时
public int storeData(Database db, int num) throws JSONException {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://www.example.com/file.json");
request.addHeader("Cache-Control", "no-cache");
long id = -1;
try {
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
InputStreamReader in = new InputStreamReader(entity.getContent());
BufferedReader reader = new BufferedReader(in);
StringBuilder stringBuilder = new StringBuilder();
String line = "";
while ((line=reader.readLine()) != null) {
stringBuilder.append(line);
}
JSONArray jsonArray = new JSONArray(stringBuilder.toString());
SQLiteDatabase dbWrite = db.getWritableDatabase();
ContentValues values = new ContentValues();
if (jsonArray.length() == num && num != 0)
return num;
SQLiteDatabase dbread = db.getReadableDatabase();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jObj = (JSONObject) jsonArray.getJSONObject(i);
values.put("id", jObj.optString("id").toString());
values.put("name", jObj.optString("firstname").toString());
values.put("surname",jObj.optString("lastname").toString());
id = dbWrite.insert("users", null, values);
}
num = jsonArray.length();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (id > 0)
return num;
else
return -1;
}
+0
@ashoke大型传输比其他任何类型的传输都更不可能。一些新数据在每次读取的超时时间内到达,否则不会。但是,这个单一的陈述是唯一错误的,否则你的优秀和正确的答案。我已投票拒绝删除它。 –
2014-10-10 23:21:25
+0
我还没有解决...我会再次看到你的答案...如何做到这一点? –
2014-10-11 07:52:37
+0
@EJP我只是指出我们需要一种方式来取消大型转移中。 'smartmouse',我没有删除看到下面 –
2014-10-11 18:44:28