我正在尝试编写可以读取JSONArray的代码,但是互联网服务器可能已关闭,设备无法连接,或者设备上没有互联网连接。
如何优雅地响应用户,因为我的异常catch块中的return语句似乎不起作用。
这是我的代码。
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;
}
答案 0 :(得分:1)
只需使用Toast
说出问题所在。例如“无法建立连接”
答案 1 :(得分:0)
我是这样做的:
ConnectivityManager cm = (ConnectivityManager)this.getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo ni =cm.getActiveNetworkInfo();
if(ni==null){
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.dialog);
dialog.setTitle("No Internet Connection");
dialog.show();
dialog.setCancelable(false);
Button settings = (Button) dialog.findViewById(R.id.settings);
Button exit = (Button) dialog.findViewById(R.id.exitApp);
Button retry = (Button) dialog.findViewById(R.id.retry);
settings.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
startActivity(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS));
}
});
exit.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
dialog.cancel();
MainActivity.this.finish();
}
});
retry.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
dialog.cancel();
MainActivity.this.finish();
Intent newActivity = new Intent(getApplicationContext(), MainActivity.class);
startActivity(newActivity);
}
});
答案 2 :(得分:0)
如果你有
,捕获量将如何发挥作用throw new RuntimeException("Failed : HTTP error code : "
+ httpResponse.getStatusLine().getStatusCode());
如果你的代码告诉操作系统抛出它会抛出,你还能指望什么呢?