无法下载网页内容

时间:2019-09-21 19:20:53

标签: java android-asynctask httpsurlconnection

我是Java和android的新手,作为我正在做的课程的一部分,我必须将网页的内容下载到Log中。但是我无法正常工作。我遇到了错误:  无法启动活动ComponentInfo NullPointerException

我正在使用Android Studio 3.5

谢谢。

我已经尝试将课程代码与课程代码进行核对,并与之匹配。

    package com.android.guessthecelebrity;

import androidx.appcompat.app.AppCompatActivity;

import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutionException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MainActivity extends AppCompatActivity {


    public class downloadTask extends AsyncTask<String, Void, String>{
        @Override
        protected String doInBackground(String... urls) {
        String result = "";
        URL url;
        HttpURLConnection urlConnection = null;

        try {
            url = new URL(urls[0]);
            urlConnection = (HttpURLConnection)url.openConnection();
            InputStream in = urlConnection.getInputStream();

            InputStreamReader reader = new InputStreamReader(in);
            int data  = reader.read();

            while (data != -1) {

                char current = (char)data;
                result += current;
                data= reader.read();
            }

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

        return null;
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        downloadTask task = new downloadTask();
        String result = null;
        try {
            result = task.execute("http://www.posh24.se/kandisar").get();

            String [] splitResult = result.split("<div class=\"sidebarContainer\">");
            Pattern p = Pattern.compile("src=\"(.*?)\"");
            Matcher m = p.matcher(splitResult[0]);// [0] refers to the part before the split point

            while (m.find()) {
                System.out.println(m.group(1));

            }

            p = Pattern.compile("alt=\"(.*?)\"");
            m = p.matcher(splitResult[0]);// [0] refers to the part before the split point


            System.out.println(m.group(1));

        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


    }
}

我希望将网页内容返回到日志

1 个答案:

答案 0 :(得分:0)

好吧,奥利弗(Oliver),我是新来的,在您被吸引之前,请帮助我

欢迎使用StackOverflow:)

“问题”中没有太多错误日志,但是该错误确实告诉您,由于得到NullPointerException而未初始化该对象之一(欢迎使用Java中最常见的错误)。

我整理了一些代码,可以在这里为您提供帮助。

没什么要注意的,

  • 确保您的活动存在于AndroidManifest.xml文件中。
  • 这是<uses-permission android:name="android.permission.INTERNET" />存在于您的AndroidManifest.xml文件中。

    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.util.Log;
    import android.widget.TextView;
    
    import androidx.appcompat.app.AppCompatActivity;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.nio.charset.StandardCharsets;
    
    import your.package.name.R;
    
    
    public class GetWebContentActivity extends AppCompatActivity {
    
    
    
    private static final String TAG = "GetWebContent";
    
    private TextView webContentTextView;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_get_web_content);
        setSupportActionBar(findViewById(R.id.toolbar));
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    
        webContentTextView = findViewById(R.id.web_content_text_view);
        (new GetWebContent()).execute("https://www.google.com/"); //argument is the website link
    
    }
    
    class GetWebContent extends AsyncTask<String, Void, String> {
    
        private String webContentResult = "Couldn't get web content";
    
        @Override
        protected String doInBackground(String... strings) {
    
            String urlOfTheWebsite = strings[0];
    
            try {
                URL url = new URL(urlOfTheWebsite);
    
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
    
                InputStream inputStream = httpURLConnection.getInputStream();
    
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
    
                String tempText = null;
                StringBuilder stringBuilder = new StringBuilder();
                while ((tempText = bufferedReader.readLine()) != null) {
                    stringBuilder.append(tempText);
                }
    
                webContentResult = stringBuilder.toString();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return webContentResult;
        }
    
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
    
            Log.d(TAG, "" + s); // you may log the web content like this
            //or
            webContentTextView.setText("" + s); // print this on UI
        }
    
    }
    }
    

  • 请尝试检查您在Google(StackOverflow)上遇到的每个错误
  • 尝试考虑编码的紧密反馈循环,当您获得编码时,您将尽快发现任何错误。
  • 如果您是Java新手,请考虑一些教程(Practical Programming)。
  • Java是一种Typed语言,是学习编程的好地方,但是,如果您想使用Android,请考虑使用Kotlin语言
  • 在问一个问题之前要做些功课,这会在Stack-overflow中带来收获,
  • 请尽可能帮助他人。