java - 如何从android java中的网页获取信息

标签 java android webpage bufferedreader

我一直在尝试将网页中的信息转换为字符串并发送到我的 Android 应用程序中。我一直在使用这种方法。

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;


public class DownloadPage {

    private static int arraySize;

    public static int getArraySize() throws IOException {

        URL url = new URL("http://woah.x10host.com/randomfact2.php");

        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        InputStream in = new BufferedInputStream(urlConnection.getInputStream());
        BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));

        String size = br.readLine();

        arraySize = Integer.parseInt(size);

        return arraySize;
    }



}

我什至在我的 AndroidManifest.xml 文件中包含了权限

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

但是我不断收到错误消息,我的应用程序无法启动。每次我调用方法或类时它都会崩溃。

最佳答案

您似乎遇到了 android.os.NetworkOnMainThreadException。 请尝试使用 AsyncTask 获取该整数。

public class DownloadPage {

    private static int arraySize;

    public void getArraySize() throws IOException {

        new RetrieveInt().execute();
    }

    private class RetrieveInt extends AsyncTask<String, Void, Integer> {


        @Override
        protected Integer doInBackground(String ... params) {
            try {
                URL url = new URL("http://woah.x10host.com/randomfact2.php");

                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));

                String size = br.readLine();

                arraySize = Integer.parseInt(size);


            } catch (Exception e) {
                //do something
            }
            return arraySize; // gets 18
        }


        protected void onPostExecute(Integer i) {

            // TODO: do something with the number
// You would get value of i == 18 here. This methods gets called after your doInBackground() with output.
            System.out.println(i); 
        }
    }


}

关于java - 如何从android java中的网页获取信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32026053/

相关文章:

html - 如何防止显示器在观看 html 5 动画时休眠

java - 如何使用 logback 关闭 STDOUT 形式的 Soap 消息 CXF

Android 应用程序未安装到设备上

android - 停止ListView滚动动画

android - 每次位置更改时更新 googlemap 相机位置

email - 为什么在电子邮件中写 'at' 和 'dot' 而不是 '@' 和 '.' ?

vba - 使用 Excel VBA 读取网页

java - openGL 中的 VBO

java - 一个 ScrollView 只能有一个子 Android XML 文件

java - 使用 JDBC 将 Android 连接到 SQL Server