Java Android-如何处理异步Http崩溃

Java Android-如何处理异步Http崩溃,java,android,android-asynctask,http-post,apache-httpclient-4.x,Java,Android,Android Asynctask,Http Post,Apache Httpclient 4.x,我的应用程序当前在无法连接到服务器时崩溃。我如何处理这个问题,而是让用户知道服务器已关闭并重试 private void sendPostRequest(String givenEmail, String givenPassword) { class SendPostRequestTask extends AsyncTask<String, Void, String> { @Override protected String doInBac

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

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);
}
private void sendPostRequest(字符串givenEmail,字符串givenPassword){
类SendPostRequestTask扩展了AsyncTask{
@凌驾
受保护的字符串doInBackground(字符串…参数){
字符串emailInput=params[0];
字符串密码输入=参数[1];
字符串jsonUserInput=“{email:+emailInput+”,密码:
+密码输入+“}”;
试一试{
HttpClient HttpClient=新的DefaultHttpClient();
//仅将网页URL用作
//HttpPost参数,因为它是post方法。
HttpPost HttpPost=新的HttpPost(服务器URL);
//我们添加了我们希望在帖子中传递的内容
//作为名称-值对的请求
json=新的JSONObject(jsonUserInput);
jsonString=newStringEntity(json.toString());
setEntity(jsonString);
setHeader(“接受”、“应用程序/json”);
setHeader(“内容类型”、“应用程序/json”);
HttpParams httpParameters=httpPost.getParams();
//以毫秒为单位设置超时,直到建立连接。
int timeoutConnection=1000;
HttpConnectionParams.setConnectionTimeout(httpParameters,timeoutConnection);
//设置默认套接字超时(SO\U超时)
//以毫秒为单位,这是等待数据的超时。
int timeoutSocket=1000;
HttpConnectionParams.setSoTimeout(httpParameters,timeoutSocket);
//HttpResponse是一个与HttpPost类似的接口。
//因此,我们无法初始化它们
HttpResponse HttpResponse=httpClient.execute(httpPost);
//根据JavaAPI,InputStream构造函数
//没什么。
//因此,我们无法初始化InputStream,尽管它不是
//接口
InputStream InputStream=httpResponse.getEntity()
.getContent();
InputStreamReader InputStreamReader=新的InputStreamReader(
输入流);
BufferedReader BufferedReader=新的BufferedReader(
输入流阅读器);
StringBuilder StringBuilder=新的StringBuilder();
字符串bufferedStrChunk=null;
while((bufferedStrChunk=bufferedReader.readLine())!=null){
追加(bufferedStrChunk);
}
返回stringBuilder.toString();
}捕获(客户端协议异常cpe){
Log.i(登录名,“ClientProtocolException”);
printStackTrace();
}捕获(ConnectTimeoutException e){
e、 printStackTrace();
}捕获(ioe异常ioe){
Log.i(登录,“IOException”);
ioe.printStackTrace();
}捕获(JSONException e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
返回null;
}
@凌驾
受保护的void onPostExecute(字符串结果){
super.onPostExecute(结果);
Log.i(登录,结果);
试一试{
serverResponse=新的JSONObject(结果);
}捕获(JSONException e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
试一试{
if((serverResponse.has(“status”))
&&(serverResponse.get(“status”).toString()
.等于(“200”)){
Toast.makeText(getApplicationContext(),“SUCCESS!”,
Toast.LENGTH_LONG).show();
}否则{
Toast.makeText(getApplicationContext(),
“不正确的电子邮件/密码!!!”,
Toast.LENGTH_LONG).show();
}
}捕获(JSONException e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
}
}
SendPostRequestTask SendPostRequestTask=新建SendPostRequestTask();
sendPostRequestTask.execute(givenEmail,givenPassword);
}
LogCat错误日志 11-11 16:26:14.970:I/R.id.login_按钮(17379):IOException 11-11 16:26:14.970:W/System.err(17379):org.apache.http.conn.HttpHostConnectException:到http://*的连接被拒绝
11-11 16:26:14.980:W/System.err(17379):在org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:183)

我可以看到您已经捕捉到了
异常,并且在PostExecute上有一个
字符串作为
的参数类型。无论何时发生错误,都可以从异常内部将类似“error”的字符串传递给
onPostExecute
。在
onPostExecute
中,您可以检查:

if the string is equal to "error":
    then create a Alert dialog box from within `onPostExecute` and show it. 
else:
    continue as desired
理想情况下,
boolean
可以实现这一点,但既然您已经有了字符串,也可以使用它。否则,您可以使用带有字符串和布尔值的
struct
,然后将其传递给
onPostExecute
。希望它能为您提供思路。

您可以使用它简化一切,并包括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();
                            }
                        }));

也可以创建新对象

 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;
    }
}


你打算怎么处理?发生异常时的预期行为是什么?我只是不希望我的应用程序完全崩溃。相反,我想显示一个对话框或类似的东西,并允许
return new AsyncTaskResult<String>(result)
return new AsyncTaskResult<String>(exception)
asynctaskresult.getError() != null