下面的代码在Java 6(以及更早版本)下工作正常,但在更新到JRE 7(Java 7)后停止工作。
URL是FTP文件:
内容长度返回-1:
为解决这个问题,可以检查getResponseCode方法的返回值,并适当处理-1的情况,例如打开新连接或在流上调用getErrorStream方法。 不兼容性质:行为 请求增强功能(RFE):7055058
问题显然出现在getContentLength()方法上。 使用JRE6时,此方法返回一个值,但使用JRE7时,我得到了-1。
URL是FTP文件:
这是我得到的输出:ftp://ftp-private.ncbi.nlm.nih.gov/pubchem/.fetch/96/4133257873201306969.sdf.gz
这是我的代码:application/octet-stream -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。