[英]How to display web service errors using toast (Android)
如何处理网络服务错误(例如500或404)并在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.makeText(getBaseContext(),"JSON - Failed to download file"+status_code,
Toast.LENGTH_LONG).show();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getBaseContext(), "JSON - Failed to download file", Toast.LENGTH_LONG).show();
}
});
问题解决了
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.