HTTPPost 失败时取消 AsyncTask?

发布于 2024-11-02 16:50:59 字数 1899 浏览 2 评论 0原文

当连接到服务器失败时,我试图取消我的 AsyncTask。我尝试了 cancel(),但仍然调用 onPostExecute() 方法,而不是 onCancelled()

这就是我在 doInBackground() 中的内容:

    protected String doInBackground(String... params) {
        Log.i("ping", "doInBackground() started");

        DefaultHttpClient client = new DefaultHttpClient();
        HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);

        HttpResponse response;
        HttpEntity entity;

            try {
                HttpPost post = new HttpPost("http://192.168.1.6/ping/login.php");

                List<NameValuePair> nvps = new ArrayList<NameValuePair>();
                nvps.add(new BasicNameValuePair("username", getEmail()));
                nvps.add(new BasicNameValuePair("password", getPassword()));

                post.setHeader("Content-Type", "application/x-www-form-urlencoded");
                post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

                response = client.execute(post);
                entity = response.getEntity();

                InputStream iStream = entity.getContent();
                read(iStream);
                iStream.close();

                if(entity != null)
                    entity.consumeContent();

                Log.i("ping", "doInBackground() vervolgd");


            } catch (Exception e) {
                e.printStackTrace();
                Log.e("tvsping", "Exception: " + e.getMessage());
                cancel(true);
            }
        return null;
    }

我试图看看当无法访问服务器时会发生什么(我正在将其关闭,所以我的手机无法获取任何信息)响应),我收到 IOException:连接已重置。

有什么想法我应该如何检查连接是否未建立?

更新 我按照 Tanmay 的建议用布尔值解决了这个问题。但我还有另一个问题: 每次调用 doInBackground() 时,当找不到服务器时,大约需要三分钟才能停止。当它可以到达服务器时一切都很好,但是我不能让用户在收到任何通知之前花费 3 分钟(我可以做一个后台进程,但仍然 3 分钟的等待栏也不好)

有什么想法吗我的代码有问题吗?这不可能是正常的吧?

I'm trying to cancel my AsyncTask when connecting to the server fails. I tried cancel(), but the onPostExecute() method still gets called, instead of onCancelled().

This is what I have inside doInBackground():

    protected String doInBackground(String... params) {
        Log.i("ping", "doInBackground() started");

        DefaultHttpClient client = new DefaultHttpClient();
        HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);

        HttpResponse response;
        HttpEntity entity;

            try {
                HttpPost post = new HttpPost("http://192.168.1.6/ping/login.php");

                List<NameValuePair> nvps = new ArrayList<NameValuePair>();
                nvps.add(new BasicNameValuePair("username", getEmail()));
                nvps.add(new BasicNameValuePair("password", getPassword()));

                post.setHeader("Content-Type", "application/x-www-form-urlencoded");
                post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

                response = client.execute(post);
                entity = response.getEntity();

                InputStream iStream = entity.getContent();
                read(iStream);
                iStream.close();

                if(entity != null)
                    entity.consumeContent();

                Log.i("ping", "doInBackground() vervolgd");


            } catch (Exception e) {
                e.printStackTrace();
                Log.e("tvsping", "Exception: " + e.getMessage());
                cancel(true);
            }
        return null;
    }

I'm trying to see what happens when the server can't be reached (I'm shutting it down, so there's no way my phone is getting any response) and I get IOException: the connection was reset.

Any ideas how I should check if the connection isn't made?

update
I solved this like Tanmay suggested, with a boolean. But I have another problem:
Every time doInBackground() is called it takes about three minutes to stop, when it can't find the servers. Everything is fine when it can reach the server, but I can't have this taking 3 minutes before the user is notified of anything (I could do a background process, but still a 3 minute wating bar is no good neither)

Any ideas what is wrong with my code? This can't be normal, right?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

送舟行 2024-11-09 16:50:59

doInBackground() 方法中,您将返回一个 String 。如果您的 HTTPPost 失败,您可以返回 null 。然后在 onPostExecute() 方法中,只需检查您得到了什么,如果 String 为 null,则不要执行任何您真正想要的操作,并在成功运行后执行 UI 工作

希望这会有所帮助你。

From doInBackground() method you are returning a String .You can return null if your HTTPPost fails.And then in onPostExecute() method just check what are you getting, if the String is null dont do anything which you really want and on successful running do your UI work

Hope this will help you.

不美如何 2024-11-09 16:50:59
HttpHost target = new HttpHost("192.168.2.3", 80);
HttpPost post = new HttpPost("/ping/login.php");

response = client.execute(target, post);

这为我解决了服务器响应缓慢的问题。

HttpHost target = new HttpHost("192.168.2.3", 80);
HttpPost post = new HttpPost("/ping/login.php");

response = client.execute(target, post);

This solved the slow server response for me.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文