简体   繁体   中英

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. 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

<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 . Please try it using AsyncTask for getting that integer.

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. 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.

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. And use logcat to see webserver data

Since your error is accessing the webserver in the main thread you have to use an AsynTask for it as answered by Amey. You will have a problem then to use the int found in your code unless you update it a little bit.

You can 'pauze' your app to wait for the AsynTask to finish but that would defeat the purpose of using an AsyncTask. AsyncTasks are made to let your app continue without having to wait for slow functions to finish.

To use you array size add in onPostExecute a function DownloadPage.this.useArrayLength(i) and add to DownloadPage

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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