有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java将整个网站内容放入字符串值(安卓)

我有一个任务要对整个网站的内容进行hashcode(点击按钮),我已经进入了死胡同(因为我是初学者)。到目前为止,我成功地做到了这一点:

public class MainActivity extends Activity {

    Button btn;
    EditText urlInput;
    TextView urlTxt, hashValue, saveLoc, tv4;


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

        btn = (Button) findViewById(R.id.btn);
        urlInput = (EditText) findViewById(R.id.urlInput);

        urlTxt = (TextView) findViewById(R.id.urlTxt);
        hashValue = (TextView) findViewById(R.id.hashValue);
        saveLoc = (TextView) findViewById(R.id.saveLoc);
        tv4 = (TextView) findViewById(R.id.tv4);

    }


    public void btnClick(View v) throws IOException, NoSuchAlgorithmException {

        Button btn = (Button) v;

        urlTxt.setText("Url entered: " + urlInput.getText());
        String urlCopy = urlInput.getText().toString();

        //problem area ahead ->
        URL uri = new URL(urlCopy);
        URLConnection ec = uri.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(ec.getInputStream(), "UTF-8"));
        String inputLine;
        StringBuilder a = new StringBuilder();
        while ((inputLine = in.readLine()) != null)
            a.append(inputLine);
        in.close();

        int hashedSite = inputLine.hashCode();
        hashValue.setText("Hash Value: " + hashedSite);


        BigInteger bi = BigInteger.valueOf(hashedSite);
        byte[] bytes = bi.toByteArray();
        if ((bytes[0] % 2) == 0) {
            tv4.setText("First byte is an even number: " + bytes[0]);
        } else {
            tv4.setText("First byte is and odd number: " + bytes[0]);
        }


        //        String out = new Scanner(new URL(urlCopy).openStream(), "UTF-8").useDelimiter("\\Z").next();
    }
}

我被卡住的地方是缓冲阅读器,我无法让它从编辑文本字段读取web URL。最后一条评论是我尝试过的事情之一,但对我来说也没有效果。问题是为什么缓冲读取器不读取并保存URL

作业还要求我检查散列网站的第一个字节,并将其写入数据库(如果是偶数)或SharedReference(如果是奇数)中,但我稍后会尝试找出答案


共 (1) 个答案

  1. # 1 楼答案

    a变量中,您发布的代码存储了网页内容。inputLine将包含in.readLine()返回的最后一个值,即null

    你需要改变

    int hashedSite = inputLine.hashCode();
    

    int hashedSite = a.toString().hashCode();
    

    而且,你似乎已经在UI线程上运行了所有这些。在安卓系统中,与网络相关的任务应该在后台线程上完成。你应该看看AsyncTask