1

每当无法连接到服务器时,我的应用程序当前就会崩溃。我该如何处理,而是让用户知道服务器已关闭并重试。

private void sendPostRequest(String givenEmail, String givenPassword) {

    class SendPostRequestTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {

            String emailInput = params[0];
            String passwordInput = params[1];

            String jsonUserInput = "{email: " + emailInput + ", password: "
                    + passwordInput + "}";

            try {

                HttpClient httpClient = new DefaultHttpClient();

                // Use only the web page URL as the parameter of the
                // HttpPost argument, since it's a post method.
                HttpPost httpPost = new HttpPost(SERVER_URL);

                // We add the content that we want to pass with the POST
                // request to as name-value pairs

                json = new JSONObject(jsonUserInput);

                jsonString = new StringEntity(json.toString());

                httpPost.setEntity(jsonString);

                httpPost.setHeader("Accept", "application/json");
                httpPost.setHeader("Content-type", "application/json");

                HttpParams httpParameters = httpPost.getParams();
                // Set the timeout in milliseconds until a connection is established.
                int timeoutConnection = 1000;
                HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
                // Set the default socket timeout (SO_TIMEOUT) 
                // in milliseconds which is the timeout for waiting for data.
                int timeoutSocket = 1000;
                HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

                // HttpResponse is an interface just like HttpPost.
                // Therefore we can't initialize them
                HttpResponse httpResponse = httpClient.execute(httpPost);

                // According to the JAVA API, InputStream constructor does
                // nothing.
                // So we can't initialize InputStream although it is not an
                // interface
                InputStream inputStream = httpResponse.getEntity()
                        .getContent();

                InputStreamReader inputStreamReader = new InputStreamReader(
                        inputStream);

                BufferedReader bufferedReader = new BufferedReader(
                        inputStreamReader);

                StringBuilder stringBuilder = new StringBuilder();

                String bufferedStrChunk = null;

                while ((bufferedStrChunk = bufferedReader.readLine()) != null) {
                    stringBuilder.append(bufferedStrChunk);
                }

                return stringBuilder.toString();

            } catch (ClientProtocolException cpe) {
                Log.i(LOGIN, "ClientProtocolException");
                cpe.printStackTrace();
            } catch (ConnectTimeoutException e) {
                e.printStackTrace();
            } catch (IOException ioe) {
                Log.i(LOGIN, "IOException");
                ioe.printStackTrace();
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);

            Log.i(LOGIN, result);

            try {
                serverResponse = new JSONObject(result);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            try {
                if ((serverResponse.has("status"))
                        && (serverResponse.get("status").toString()
                                .equals("200"))) {
                    Toast.makeText(getApplicationContext(), "SUCCESS!",
                            Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(getApplicationContext(),
                            "Incorrect Email/Password!!!",
                            Toast.LENGTH_LONG).show();
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    SendPostRequestTask sendPostRequestTask = new SendPostRequestTask();
    sendPostRequestTask.execute(givenEmail, givenPassword);
}

LogCat 错误日志

11-11 16:26:14.970: I/R.id.login_button(17379): IOException 11-11 16:26:14.970: W/System.err(17379): org.apache.http.conn.HttpHostConnectException: Connection到 http:// *拒绝 11-11 16:26:14.980: W/System.err(17379): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:183)

4

3 回答 3

0

我可以看到您已经Exceptions掌握了 并且有一个Stringas 参数类型 to onPostExecute。从异常内部onPostExecute,只要发生错误,您就可以将“error”之类的字符串传递给 。在里面onPostExecute你可以检查:

if the string is equal to "error":
    then create a Alert dialog box from within `onPostExecute` and show it. 
else:
    continue as desired

理想情况下 aboolean可以解决问题,但由于您已经有一个字符串,您也可以使用它。否则,您可以使用struct带有字符串和布尔值的 a,然后将其传递给onPostExecute. 希望它给你的想法。

于 2013-11-12T01:21:51.740 回答
0

您可以使用droidQuery来简化一切并包括 HTTP 错误处理:

$.ajax(new AjaxOptions().url("http://www.example.com")
                        .type("POST")
                        .dataType("json")
                        .header("Accept", "application/json")
                        .header("Content-type", "application/json")
                        .timeout(1000)
                        .success(new Function() {
                            @Override
                            public void invoke($ d, Object... args) {
                                Toast.makeText(this, "SUCCESS!", Toast.LENGTH_SHORT).show();
                                JSONObject serverResponse = (JSONObject) args[0];
                                //handle response
                            }
                        })
                        .error(new Function() {
                            @Override
                            public void invoke($ d, Object... args) {
                                AjaxError error = (AjaxError) args[0];
                                //toast shows the error code and reason, such as "Error 404: Page not found"
                                Toast.makeText(this, "Error " + error.status + ": " + error.reason, Toast.LENGTH_SHORT).show();
                            }
                        }));
于 2013-11-12T14:11:07.503 回答
0

或者您可以创建新对象

 public class AsyncTaskResult<T> {
    private T result;
    private Exception error;

    public T getResult() {
        return result;
    }
    public Exception getError() {
        return error;
    }

    public AsyncTaskResult(T result) {
        super();
        this.result = result;
    }

    public AsyncTaskResult(Exception error) {
        super();
        this.error = error;
    }

    public void setError(Exception error) {
        this.error = error;
    }
}

并将其传递给onPostExecute

return new AsyncTaskResult<String>(result)

或者

return new AsyncTaskResult<String>(exception)

onPostExecute你可以检查异常是否存在

asynctaskresult.getError() != null
于 2013-11-13T01:31:52.967 回答