我在使用 InputStream 时遇到了一些问题。我正在编写一个小的 Android 应用程序,其中一部分必须从网站获取 HTML 代码。一般来说,它工作正常,但有时(通常是第二次调用,但也可能需要几次尝试重现)它会跳过 InputStream(我注意到这一点,因为它在调试时需要几秒钟,但每次它失败了,它会立即跳到下一行)。任何想法可能导致此问题以及如何解决它?
private class fetchdata extends AsyncTask<Void, Void, Void> {
public Activity activity;
public fetchdata(Activity a)
{
activity = a;
}
protected Void doInBackground(Void...voids)
{
String[] page = new String[16384]; //Number is just for testing, don't worry
try {
page = executeHttpGet();
} catch (Exception e) {
page[0] = "Error";
}
displayFetchedData(page);
return null;
}
public String[] executeHttpGet() throws Exception {
URL u;
InputStream is = null;
DataInputStream dis = null;
String s;
int i = 0;
int hostselection;
boolean skip;
String[] page = new String[16384];
String[] serverurls = new String[2];
addSecurityException();
SharedPreferences dataprefs = getSharedPreferences("serverdata", Context.MODE_PRIVATE);
hostselection = dataprefs.getInt("selectedhost", 0);
SharedPreferences preferences;
preferences = PreferenceManager.getDefaultSharedPreferences(activity);
serverurls[0] = preferences.getString("server01", "");
serverurls[1] = preferences.getString("server02", "");
for (int j = 0; j < 2; j++)
{
skip = false;
if (j == 0)
{
if (hostselection == 0 || hostselection == 1)
{
Authenticator.setDefault(new MyAuthenticator(activity, false));
}
else
{
skip = true;
}
}
if (j == 1)
{
if (hostselection == 0 || hostselection == 2)
{
Authenticator.setDefault(new MyAuthenticator(activity, true));
}
else
{
skip = true;
}
}
if (skip == false)
{
try {
u = new URL(serverurls[j]);
is = u.openStream(); //LINE IN QUESTION
dis = new DataInputStream(new BufferedInputStream(is));
while ((s = dis.readLine()) != null)
{
if (s.length() > 18)
{
page[i] = s;
i++;
}
}
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
is.close();
}
}
return page;
}
最佳答案
从您获得的输入流中创建一个BufferedInputStream
,然后调用mark()
以输入流长度作为参数的方法。下次需要重用流时调用reset()
。
关于java - 如果多次使用,InputStream 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7330943/