如何从Android Java中的网页获取信息
作者:互联网
香港专业教育学院一直试图从网页上获取信息成字符串到我的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);
}
}
}
标签:webpage,bufferedreader,java,android 来源: https://codeday.me/bug/20191119/2039469.html