有时当我尝试从我的应用程序的后台服务调用api时,连接未建立,我可以从我的日志中看到IOException消息(网络错误)。
AndroidHttpClient client = null;
try {
// Create the end-point client
client = AndroidHttpClient.newInstance("TCR Software Android Application");
HttpConnectionParams.setConnectionTimeout(client.getParams(), 30000); // 10000
HttpConnectionParams.setSoTimeout(client.getParams(), 30000); // 10000
// Execute the request
Log.v("RESTClient", "executing " + request.getMethod() + " " + request.getURI());
HttpResponse response = client.execute(request);
// Get response wrapper
responseBody = EntityUtils.toString(response.getEntity());
JSONObject responseWrapper = new JSONObject(responseBody);
//JSONObject responseWrapper = new JSONObject(EntityUtils.toString(response.getEntity()));
// Check result type
if (!responseWrapper.has("ResultType")) throw new RESTClientException(responseWrapper.getString("Message"), Reason.SERVICE_ERROR);
// Get the data object
Object responseData = responseWrapper.isNull("Data") ? null : responseWrapper.get("Data");
// Check for su
if (responseWrapper.getInt("ResultType") != 1) throw new RESTClientException(responseData == null ? responseWrapper.getString("Message") : responseData.toString(), Reason.APPLICATION_ERROR);
// Always return JSONArray
if (responseData == null)
return new JSONArray();
if (responseData instanceof JSONObject)
return new JSONArray().put(responseData);
else if (responseData instanceof JSONArray)
return (JSONArray)responseData;
else if (responseData instanceof Boolean)
return new JSONArray().put(responseData);
else if (responseData instanceof Date)
return new JSONArray().put(responseData);
else if (responseData instanceof String)
return new JSONArray().put(responseData);
else if (responseData instanceof Integer)
return new JSONArray().put(responseData);
else
{
Log.e("RESTClient", "Unexpected data format returned by server\n" + responseBody);
throw new RESTClientException("Unexpected data format returned by server. ", Reason.PROTOCOL_ERROR);
}
} finally {
if (client != null) client.close();
}
} catch (JSONException e) {
Log.e("RESTClient", "Unintelligible response from server\n" + responseBody, e);
throw new RESTClientException("Unintelligible response from server", Reason.PROTOCOL_ERROR, e);
} catch (ClientProtocolException e) {
throw new RESTClientException("Incompatible server protocol", Reason.SERVICE_ERROR, e);
} catch (UnsupportedEncodingException e) {
throw new RESTClientException("Failure encoding request data", Reason.INTERNAL_ERROR, e);
} catch (IOException e) {
throw new RESTClientException("Network error", Reason.NO_CONNECTION);
}
如果发生IOException,我将显示网络错误消息。但是如何解决这个问题却没有发生。将setConnectionTimeout,setSoTimeout值增加到60秒有助于解决这个问题吗?