简体   繁体   English

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

[英]How to get information from a webpage in android java

Ive been trying to get information from a webpage into a string onto my android app. 我一直试图从网页上获取信息到我的Android应用程序的字符串。 Ive been using this method. 我一直在使用这种方法。

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;
    }



}

Ive even included the permission in my AndroidManifest.xml file 我甚至在AndroidManifest.xml文件中包含了权限

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

However i keep getting errors and my app will not launch. 但是我不断收到错误,我的应用程序将无法启动。 It crashes every time i call up the method or the class. 每次调用方法或类时它都会崩溃。

You seem to be getting android.os.NetworkOnMainThreadException . 你似乎得到android.os.NetworkOnMainThreadException Please try it using AsyncTask for getting that integer. 请使用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); 
        }
    }


}

Issue may be in below code: 问题可能在以下代码中:

String size = br.readLine();
arraySize = Integer.parseInt(size);

You are trying to parse string to integer. 您正在尝试将字符串解析为整数。 Check if br.readLine() contains only integer value. 检查br.readLine()是否仅包含整数值。 If string has non-numeric characters then issue will occur. 如果字符串具有非数字字符,则会发生问题。

If you know which part of line contains the size, you can get substring and then parse it to int. 如果您知道行的哪一部分包含大小,则可以获取子字符串,然后将其解析为int。

Try below: 试试以下:

String resposne = br.readLine();
// If you are sure that array length is only 2 digits.
String length = response.subString(0,2);
arraySize = Integer.parseInt(length);

You cannot connect android app and web server in main ui thread use handeler or aynstask. 你无法在主ui线程中使用handeler或aynstask连接android app和web server。 And use logcat to see webserver data 并使用logcat查看Web服务器数据

Since your error is accessing the webserver in the main thread you have to use an AsynTask for it as answered by Amey. 由于您的错误是访问主线程中的Web服务器,因此必须使用AsynTask作为Amey的回答。 You will have a problem then to use the int found in your code unless you update it a little bit. 您将遇到一个问题,即使用代码中的int,除非您稍微更新它。

You can 'pauze' your app to wait for the AsynTask to finish but that would defeat the purpose of using an AsyncTask. 您可以“暂停”您的应用程序以等待AsynTask完成,但这会破坏使用AsyncTask的目的。 AsyncTasks are made to let your app continue without having to wait for slow functions to finish. AsyncTasks用于让您的应用程序继续运行,而无需等待缓慢的功能完成。

To use you array size add in onPostExecute a function DownloadPage.this.useArrayLength(i) and add to DownloadPage 要使用你的数组大小,请在onPostExecute添加一个函数DownloadPage.this.useArrayLength(i)并添加到DownloadPage

public void useArrayLength(int length){
     //do something with length
}

在main中使用.wait(),因此它将在main之前首先处理asynctask来自这个答案: https ://stackoverflow.com/a/32026368/7469261

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM