我正在尝试编写将读取 JSONArray 的代码,但互联网服务器可能已关闭并且设备无法连接,或者设备上没有互联网连接。
我如何优雅地响应用户,因为我的异常捕获块中的返回语句似乎不起作用。
这是我的代码。
public JSONArray getJSONFromUrl(String url) {
JSONArray jArray = null;
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
if(httpResponse.getStatusLine().getStatusCode() == 200){
// Connection was established. Get the content.
HttpEntity httpEntity = httpResponse.getEntity();
// A Simple JSON Response Read
istream = httpEntity.getContent();
} else {
throw new RuntimeException("Failed : HTTP error code : "
+ httpResponse.getStatusLine().getStatusCode());
}
if(BuildConfig.DEBUG){
Log.d(Constants.LOG, "httpEntity : ");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return;
} catch (ClientProtocolException e) {
e.printStackTrace();
return;
} catch (IOException e) {
e.printStackTrace();
return;
}