0

如何处理 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 之类的错误,吐司就不会显示

4

2 回答 2

0

只需将您的状态代码附加到吐司中即可

Toast.makeText(getBaseContext(),"JSON - Failed to download file"+status_code,
                                     Toast.LENGTH_LONG).show();
于 2013-08-24T16:36:29.820 回答
0
runOnUiThread(new Runnable() {
  public void run() {
    Toast.makeText(getBaseContext(), "JSON - Failed to download file", Toast.LENGTH_LONG).show();
  }
});

问题解决了

于 2014-05-27T04:02:06.917 回答