我一直在尝试将网页中的信息转换为字符串并发送到我的 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/