我想创建一个依赖于JSON响应的android应用程序。有时,服务器需要很长时间才能响应,并以超时异常结束。因此,如果没有响应,我想添加一个限制,如我的webservice调用应在20秒后中止。你能帮我实现这个想法吗?如何避免超时异常?
在此先感谢。
我想创建一个依赖于JSON响应的android应用程序。有时,服务器需要很长时间才能响应,并以超时异常结束。因此,如果没有响应,我想添加一个限制,如我的webservice调用应在20秒后中止。你能帮我实现这个想法吗?如何避免超时异常?
在此先感谢。
你没有给出你的实际实施细节。
但是,混淆超时看起来好像它可能是一个应该修复的潜在问题的紧急修复。
但是,使用websockets进行传输可能是一种可能(也许更优雅)的解决方案。它们在创建后提供客户端和服务器之间的持久连接。
有几种方式来实现目标。
我们可以使用HttpURLConnection来做http请求。
public String doPost() {
if (!mIsNetworkAvailable) {
return null;
}
try {
URL url = new URL(mURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
for (String key : mHeadersMap.keySet()) {
conn.setRequestProperty(key, mHeadersMap.get(key));
}
conn.setRequestProperty("User-Agent", "Android");
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setRequestProperty("Content-Type", "application/json");
conn.getOutputStream().write(mContent);
conn.getOutputStream().flush();
int rspCode = conn.getResponseCode();
if (rspCode >= 400) {
return null;
}
byte[] buffer = new byte[8 * 1024];
BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int len;
while ((len = bis.read(buffer)) > 0) {
baos.write(buffer, 0, len);
}
baos.flush();
final String result = new String(baos.toByteArray());
baos.close();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
setConnectTimeout:以毫秒为单位的最长等待时间,同时连接。
setReadTimeout:设置在放弃之前等待输入流读取完成的最大时间。
参考:http://developer.android.com/reference/java/net/URLConnection.html
您是否尝试过用漂亮的网络库,例如[排球](https://developer.android.com/training/volley/index.html)? – makata
HttpConnectionParams.setConnectionTimeout(httpParams,20000); – rKrishna