【发布时间】:2013-05-22 16:08:47
【问题描述】:
我正在尝试编写可以读取 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;
}
【问题讨论】:
标签: android json http user-interface