You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AsyncTask未返回字符串且无报错,疑调用方式有误求助

问题排查:AsyncTask调用无返回结果且无报错

问题描述

将URL传入自定义AsyncTask类wsbRedirTest,期望获取目标页面内容,但执行后无任何结果返回,也无报错信息,推测问题出在调用方式上。

自定义AsyncTask代码实现

public class wsbRedirTest extends AsyncTask<String, Void, String> {

    private Object[] values;

    protected void onPreExecute() {

    }

    @Override
    protected String doInBackground(String... par1) {
        try {
            String myUrl = par1[0];

            URL obj = new URL(myUrl);
            HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
            conn.setReadTimeout(5000);
            conn.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
            conn.addRequestProperty("User-Agent", "Mozilla");
            conn.addRequestProperty("Referer", "google.com");

            System.out.println("Request URL ... " + myUrl);

            boolean redirect = false;

            // 通常3xx状态码代表重定向
            int status = conn.getResponseCode();
            if (status != HttpURLConnection.HTTP_OK) {
                if (status == HttpURLConnection.HTTP_MOVED_TEMP
                        || status == HttpURLConnection.HTTP_MOVED_PERM
                        || status == HttpURLConnection.HTTP_SEE_OTHER)
                    redirect = true;
            }

            System.out.println("Response Code ... " + status);

            if (redirect) {
                // 从Location头字段获取重定向URL
                String newUrl = conn.getHeaderField("Location");
                // 获取Cookie(如需登录场景使用)
                String cookies = conn.getHeaderField("Set-Cookie");

                // 重新打开新的连接
                conn = (HttpURLConnection) new URL(newUrl).openConnection();
                conn.setRequestProperty("Cookie", cookies);
                conn.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
                conn.addRequestProperty("User-Agent", "Mozilla");
                conn.addRequestProperty("Referer", "google.com");

                System.out.println("Redirect to URL : " + newUrl);
            }

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String inputLine;
            StringBuffer html = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                html.append(inputLine);
            }
            in.close();

            System.out.println("URL Content... \n" + html.toString());
            System.out.println("Done");
            return html.toString();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

MainActivity中的调用代码

String par = "www.google.com";
String content = new wsbRedirTest().execute(par);

问题分析

  1. AsyncTask调用方式错误:execute()方法返回的是AsyncTask实例本身,而非doInBackground()的返回值,直接赋值给String变量属于类型不匹配,编译阶段就应该报错。
  2. URL格式错误:传入的URL缺少http://或https://协议头,URL类解析时会抛出异常,但被doInBackground()的大try-catch捕获后仅打印栈轨迹,最终返回null,且无结果回调,导致看不到任何反馈。
  3. 缺少结果回调方法:未实现onPostExecute(),AsyncTask完成后台任务后无法将结果回调到主线程,自然无法获取到返回内容。

修复方案

  1. 修正URL格式:给传入的URL添加协议头,例如:
    String par = "https://www.google.com";
    
  2. 实现onPostExecute()回调方法:在wsbRedirTest类中添加该方法,用于接收并处理后台任务结果:
    @Override
    protected void onPostExecute(String result) {
        if (result != null) {
            System.out.println("获取到的页面内容:" + result);
            // 此处可添加UI更新逻辑,如设置TextView文本
        } else {
            System.out.println("页面内容获取失败");
        }
    }
    
  3. 修正调用逻辑:execute()无需赋值给String变量,直接执行即可:
    String par = "https://www.google.com";
    new wsbRedirTest().execute(par);
    
  4. 优化异常处理:可在catch块中添加更明确的日志信息,方便排查问题,例如:
    catch (Exception e) {
        e.printStackTrace();
        System.out.println("请求出错:" + e.getMessage());
    }
    

内容的提问来源于stack exchange,提问作者PPavesi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 02:41:26