如何处理500或404等Web服务错误并在android中的toast中显示它们,下面是我的一些代码:
public String readJSONFeed(String URL) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
try {
HttpResponse response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();
} else if (statusCode == 500) {
Toast.makeText(getBaseContext(),
"JSON - Failed to download file",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Log.d("readJSONFeed", e.getLocalizedMessage());
}
return stringBuilder.toString();
}
一旦我运行了这段代码并遇到错误,例如500,就会显示toast
答案 0 :(得分:0)
只需将url状态代码附加到全部
的吐司中Toast.makeText(getBaseContext(),"JSON - Failed to download file"+status_code,
Toast.LENGTH_LONG).show();
答案 1 :(得分:0)
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getBaseContext(), "JSON - Failed to download file", Toast.LENGTH_LONG).show();
}
});
解决问题