我正在浏览Android development tutorial。我在Java方面不是很有经验,但我发现这是一个很好的练习。无论如何,这里是应该从我的Android设备上的网站上获取数据的代码(相当多的downloadUrl会做所有事情 - 所以请帮助我):
private class DownloadXmlTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
try {
return downloadUrl(urls[0]);
} catch (IOException e) {
return getResources().getString(R.string.connection_error);
}
}
@Override
protected void onPostExecute(String result) {
try{
doEt(result);
} catch (Exception e){
System.out.println(e);
}
}
private String downloadUrl(String urlString) throws IOException {
java.net.URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(100000);
conn.setConnectTimeout(150000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
BufferedReader r = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
//conn.disconnect();
return total.toString();
}
}
在doEt()中,我只打印出我获得的字符串。但是,只有一半的网站在返回的String变量中。感谢任何帮助,谢谢!
答案 0 :(得分:0)
可能出现的问题:
尝试先尝试逐行打印
while ((line = r.readLine()) != null) {
total.append(line);
Log.i("test",line);
}