我面臨與問題有關的Http連接。 我的代碼:Http URL連接無法完全讀取
URL url = null;
try {
url = new URL(_url);
} catch (MalformedURLException e) {
}
if (url != null) {
HttpURLConnection urlConn = null;
InputStreamReader isr = null;
try {
urlConn = (HttpURLConnection)url.openConnection();
urlConn.setRequestMethod("GET");
urlConn.setConnectTimeout(45000);
if(response == HttpURLConnection.HTTP_OK) {
StringBuffer readData = new StringBuffer("");
int size = 1024;
char[] buffer = new char[size];
int len;
isr = new InputStreamReader(urlConn.getInputStream());
while ((len = isr.read(buffer, 0, size)) > 0) {
readData.append(buffer, 0, len);
}
}
}
catch(Exception e) {
}
finally {
if(urlConn != null) {
try {
urlConn.disconnect();
} catch(Exception e) {
}
}
if(isr != null) {
try {
isr.close();
} catch(Exception e) {
}
}
}
此代碼無法完全下載數據。 例如: 總大小爲:13901個字節 上面的代碼可以讀取大小:12937個字節
這裏有什麼問題?
請諮詢傢伙。
你怎麼知道它是13901字節?這是在HTTP內容長度標題中還是在查看您在磁盤上提供的文件? – Paolo 2009-12-21 08:50:31
文檔說明,當您到達流的末尾時返回-1,而不是0.即使有這種修復,我也認爲Ramp的回覆可能是您遇到問題的原因。 http://java.sun.com/j2se/1.5.0/docs/api/java/io/InputStreamReader.html#read%28char[],%20int,%20int%29 – rui 2009-12-21 09:53:39
那麼,InputStream是不允許的如果至少需要1個字節,則返回0,因此檢查'if(count> 0)'實際上是否正確。 – StaxMan 2010-10-19 16:24:41