首页 > 解决方案 > 无法通过 AsyncTask 和 inputStreamReader 获取 HTML 代码

问题描述

早上好!我正在尝试使用 AsyncTask 和 inputStreamReader 从 URL 获取 HTML 代码。因为这项工作引发了我使用 try & catch 的异常,但 ry 或 catch 都没有发生。

    public void click (View v){
        Tasking task = new Tasking();
        task.execute();
    }

(我确保我的按钮连接到代码)

    class Tasking extends AsyncTask<Integer, Integer, String>{
        @Override
        protected String doInBackground(Integer... integers) {
            InputStream inputStream;
            InputStreamReader inputStreamReader;
            char c = ' ';
            String s = "";
            URL u;

            try{
                u = new URL("https://www.google.com/");
            inputStream = u.openConnection().getInputStream();
            inputStreamReader = new InputStreamReader(inputStream);
            do{
                c = (char) inputStreamReader.read();
                s += c;
            }while(c !=-1);

            }catch (Exception e){
                e.printStackTrace();
                return "Failed";
            }
            return "?!";
        }

        @Override
        protected void onPostExecute(String s) {
            TextView textView = (TextView) findViewById(R.id.textView);
            textView.setText(s);
            super.onPostExecute(s);
        }
    }

IMG 您可以在图片中看到,即使单击没有任何变化,我也会收到以下消息:

D/NetworkSecurityConfig: No Network Security Config specified, using platform default
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
    (HTTPLog)-Static: isSBSettingEnabled false
I/zygote64: Do partial code cache collection, code=61KB, data=40KB
I/zygote64: After code cache collection, code=61KB, data=40KB
    Increasing code cache capacity to 256KB
I/zygote64: Background concurrent copying GC freed 392(31KB) AllocSpace objects, 390(13MB) LOS objects, 50% free, 10MB/20MB, paused 6.137ms total 27.526ms

提前致谢!

标签: javaandroidandroid-asynctask

解决方案


do{
   c = (char) inputStreamReader.read();
   s += c;
}while(c !=-1);

这是无限循环,因为 c 永远不等于 -1。为了获得最佳实践,您应该定义您的 UI 小部件,例如 TextView、Button onCreate 中的 Activities-onCreateView 在 Fragments 中。

因此,您可以将 StringWriter 和 BufferedReader 用于您的目的。这是您问题的完整代码。

public class MainActivity extends AppCompatActivity {

public static final String LOG_TAG = MainActivity.class.getSimpleName();
private TextView resultTextView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    resultTextView = findViewById(R.id.textView);
    new Tasking().execute();
}

class Tasking extends AsyncTask<Integer, Integer, String> {
    @Override
    protected String doInBackground(Integer... integers) {
        StringWriter sw = new StringWriter();
        try {
            URL url = new URL("https://www.google.com/");
            InputStream inputStream = url.openConnection().getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader br = new BufferedReader(inputStreamReader);
            char[] buffer = new char[1024 * 16];
            int readLength;
            while (-1 != (readLength = br.read(buffer))) {
                sw.write(buffer, 0, readLength);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "Failed";
        }
        return sw.toString();
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        Log.v(LOG_TAG, "Response:" + s);
        resultTextView.setText(s);
    }
}

}

最后,您应该记录您的响应或调试您的整个班级。这就是专业开发人员所做的。所以越多的代码越快乐。享受!


推荐阅读