我正在尝试打印网站的HTML页面源。我在第45行将String初始化为null。但是,当我尝试打印新附加的字符串时,将显示null关键字。
我尝试删除String的初始化。
public class MainActivity extends AppCompatActivity {
public class ToPrintWebSiteSource extends AsyncTask<String,Void,String>{
@Override
HttpURLConnection httpURLConnection = null;
String result = null;
try {
siteUrl = new URL(urls[0]);
httpURLConnection = (HttpURLConnection) siteUrl.openConnection();
InputStream in = httpURLConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while(data!= -1){
char character = (char) data;
result += character;
data = reader.read();
}
}
catch (Exception e) {
Log.i("Error:","The code is not working....");
e.printStackTrace();
}
return result;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String result = null;
ToPrintWebSiteSource helloWorld = new ToPrintWebSiteSource();
try {
result = helloWorld.execute("https://web.ics.purdue.edu/~gchopra/class/public/pages/webdesign/05_simple.html").get();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.i("Page Source Html:", result);
}
}
我收到的结果是:
null<html>
<head>
<title>A very simple webpage</title>
<basefont size=4>
</head>
答案 0 :(得分:3)
您应该将其设置为空字符串,而不是null。当您用null
连接字符串时,字符串“ null”被添加到其中,而不是为空。
更好的是,您甚至不应该在这里使用字符串连接。这就是StringBuilder
的作用。
HttpURLConnection httpURLConnection = null;
StringBuilder result = new StringBuilder();
char buffer[] = new char[100];
try {
siteUrl = new URL(urls[0]);
httpURLConnection = (HttpURLConnection) siteUrl.openConnection();
InputStream in = httpURLConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
for (int n; (n = reader.read(buffer)) != -1;) {
result.append(buffer, 0, n);
}
}
catch (Exception e) {
Log.i("Error:","The code is not working....");
e.printStackTrace();
}
return result.toString();
这一次将多个字符读取到一个char数组中,将字符追加到StringBuilder
上,直到读取所有数据为止。将数组的大小设置为100是任意的,如果您想一次读取更多数据,则可以使其更大。