我正在按照教程从网页下载内容。http://developer.android.com/training/basics/network-ops/connecting.html#download(代码复制在下面,所以你不必去这个链接)
它len = 500
在本例中使用,我将其更改为较大的值,例如 50000,但在试验时我意识到这种方法只会下载网页的前 4048 个字符,无论我设置多大len
。所以我想知道我是否应该使用另一种方法来下载网页内容。
其实我不是下载普通网页,我在我的服务器上放了一个php脚本在我的数据库中搜索然后编码一个json数组作为页面的内容,它不是很大,大约20,000个字符..
来自上述链接的主要代码:
// Given a URL, establishes an HttpUrlConnection and retrieves
// the web page content as a InputStream, which it returns as
// a string.
private String downloadUrl(String myurl) throws IOException {
InputStream is = null;
// Only display the first 500 characters of the retrieved
// web page content.
int len = 500; // I've change this to 50000
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
int response = conn.getResponseCode();
Log.d(DEBUG_TAG, "The response is: " + response);
is = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = readIt(is, len);
return contentAsString;
// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (is != null) {
is.close();
}
}
}
// Reads an InputStream and converts it to a String.
public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}