2014-09-04 65 views
0

我想讀取一個網站,但奇怪的是它只返回它的一部分。它只是在部分的中間結束。HttpURLConnection沒有讀取整個內容

我嘗試使用setChunkedStreamingMode方法,但它沒有改變任何東西。

HttpURLConnection connection = ((HttpURLConnection) new URL(url).openConnection()); 
connection.setDoOutput(true); 
connection.setDoInput(true); 
connection.setInstanceFollowRedirects(false); 
connection.setRequestMethod("POST"); 
// I write some data... 
String content = readInputStream(connection.getInputStream()); 

ReadInputStream方法:

private static String readInputStream(InputStream in) throws IOException { 
int len = 0; 
byte[] buffer = new byte[10000]; 
ByteArrayOutputStream byteArray = new ByteArrayOutputStream(); 
while((len = in.read(buffer)) != -1) { 
    byteArray.write(buffer,0, len); 
} 
in.close(); 

return new String(byteArray.toByteArray()); 

}

是否有某種類型的數據限制?

+0

代碼似乎是正確的,你可以檢查(通過調試),如果你傳遞給新的String(..)字節數組實際上是截斷或者它的長度是否合適? – 2014-09-04 12:44:44

+0

嗯,它的29118字節。我不知道如何檢查它是否正確...我試着用CTRL + S和它的203kB保存網頁,但我不知道這是否是檢查其大小的正確方法... – Bebras 2014-09-04 13:51:54

+0

嗯,這是相當的不同的尺寸。我問,因爲其中一個問題可能是將字節數組轉換爲字符串,如果字節數組包含一些非字符串可表示的字節,如0 – 2014-09-04 15:06:56

回答

0

有沒有問題HttpURLConnection的 試試這個:

StringBuilder stringBuilder = new StringBuilder(); 
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); 
String line; 
while ((line = reader.readLine()) != null) { 
     stringBuilder.append(line); 
} 
inputStream.close(); 
+0

它似乎沒有空白行...但它仍然不是完整的網頁。 – Bebras 2014-09-05 12:24:02