[英]How to get information from a webpage in 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);
}
}
}
问题可能在以下代码中:
String size = br.readLine();
arraySize = Integer.parseInt(size);
您正在尝试将字符串解析为整数。 检查br.readLine()是否仅包含整数值。 如果字符串具有非数字字符,则会发生问题。
如果您知道行的哪一部分包含大小,则可以获取子字符串,然后将其解析为int。
试试以下:
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);
你无法在主ui线程中使用handeler或aynstask连接android app和web server。 并使用logcat查看Web服务器数据
由于您的错误是访问主线程中的Web服务器,因此必须使用AsynTask作为Amey的回答。 您将遇到一个问题,即使用代码中的int,除非您稍微更新它。
您可以“暂停”您的应用程序以等待AsynTask完成,但这会破坏使用AsyncTask的目的。 AsyncTasks用于让您的应用程序继续运行,而无需等待缓慢的功能完成。
要使用你的数组大小,请在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.