用來工作的Java 6下的優質下面的代碼(或更早),但它停止更新到JRE 7(Java 7中)之後的工作。Java 7的URL連接故障
的URL是一個FTP文件:
ftp://ftp-private.ncbi.nlm.nih.gov/pubchem/.fetch/96/4133257873201306969.sdf.gz
這裏是輸出我得到:
應用程序/八位字節流 -1 [Ljava.lang。 StackTraceElement的; @ 5419f97c
這裏是我的代碼:
public static void store(URL url, File targetFile){
try
{
System.out.println(url);
URLConnection uc = url.openConnection();
String contentType = uc.getContentType();
System.out.println(contentType);
int contentLength = uc.getContentLength();
System.out.println(contentLength);
Settings.setDownloadSize(contentLength);
if (contentType.startsWith("text/") || contentLength == -1) {
throw new IOException("This is not a binary file.");
}
InputStream raw = uc.getInputStream();
InputStream in = new BufferedInputStream(raw);
byte[] data = new byte[contentLength];
int bytesRead = 0;
StatusPanel.updateProgrssBar(bytesRead);
int offset = 0;
while (offset < contentLength) {
bytesRead = in.read(data, offset, data.length - offset);
if (bytesRead == -1) {
break;
}
offset += bytesRead;
StatusPanel.updateProgrssBar(offset);
}
in.close();
if (offset != contentLength) {
throw new IOException("Only read " + offset + " bytes; Expected " + contentLength + " bytes");
}
FileOutputStream out = new FileOutputStream(targetFile);
out.write(data);
out.flush();
out.close();
//StatusPanel.setStatus("File has been stored at " + targetFile.toString());
//System.out.println("file has been stored at " + targetFile.toString());
}
內容長度返回-1:
Area: API: Networking
Synopsis: Server Connection Shuts Down when Attempting to Read Data When http Response Code is -1
如何使這個代碼與Java 7兼容?
說明:作爲錯誤修正爲CR 6886436的結果是,在HTTP協議處理程序將關閉到發送沒有有效的HTTP狀態行的響應的服務器的連接。發生這種情況時,嘗試讀取該連接上的數據會導致IOException。
例如,下面的代碼是有問題的:
public static void test() throws Exception {
.....
HttpURLConnection urlc = (HttpURLConnection)url.openConnection();
....
System.out.println ("Response code: " + urlc.getResponseCode());
/** Following line throws java.io.IOException: Invalid Http response
* when Response Code returned was -1
*/
InputStream is = urlc.getInputStream(); // PROBLEMATIC CODE
要解決此問題,從getResponseCode方法檢查返回值並處理-1值適當地;也許通過打開一個新的連接,或者在流上調用getErrorStream。 不相容性質:行爲 RFE:7055058
這個問題肯定是用getContentLength()
的方法。
隨着JRE6,該方法返回一個值,但與JRE7我得-1。基於對URLConnection的Java 7's Javadoc
可能值得檢查服務器返回的內容長度,例如,通過Wireshark嗅探網絡。另外,你確定相同的代碼仍然適用於Java 6嗎?即是否已經消除了您更改爲Java 7並且停止工作的巧合? – DNA
它適用於Java 6.它不是一致的。我對此100%肯定。查看添加的內容。在這種情況下,url是ftp。不是HTTP .. – lochi