即使使用asynctask方法,在获取新闻api时遇到NetworkonMainThread异常

时间:2018-06-22 04:29:39

标签: android android-studio

正如对How do I fix android.os.NetworkOnMainThreadException?的回答中所提到的,我使用了AsyncTask方法,并且仍然得到了所述异常。这是代码:

     protected StringBuffer doInBackground(String... strings) {

        URL url = null;
        try {
            url = new URL("https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=94707a0431fa4193b0fe0cee513ef17b");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        HttpURLConnection con = null;
        try {
            con = (HttpURLConnection) url.openConnection();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
            con.connect();
        } catch (IOException e) {
            e.printStackTrace();
        }
        InputStream is= null;
        try {
            is = con.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        InputStreamReader isr=new InputStreamReader(is);
        BufferedReader br=new BufferedReader(isr);
        StringBuffer sb=new StringBuffer("");
        String line = "";
        try {
            line = br.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        while(line!=null)
        {
            sb.append(line);
        }
        return sb;
    }

0 个答案:

没有答案