android建立http连接超时时间,如何在Android中添加HttpClient请求和连接超时

我正在开发我的第一个应用程序,并且我创建了以下连接到远程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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值