我从Twitter中提取图像。这些图像可达来自网址形式:检查HTTP请求中的图像有效性
https://pbs.twimg.com/media/BzQXyBJIAAIU6D0.jpg
为了获取图像,我采用下面的代码:
HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
httpConnection.setRequestMethod ("GET");
httpConnection.connect();
int code = httpConnection.getResponseCode();
if (code == HttpURLConnection.HTTP_OK){
InputStream is = url.openStream();
OutputStream os = new FileOutputStream(destinationFile);
byte[] b = new byte[2048];
int length;
while ((length = is.read(b)) != -1) {
os.write(b, 0, length);
}
is.close();
os.close();
httpConnection.disconnect();
}
然而,有时会发生图像像这样:
https://pbs.twimg.com/media/By_ui7QIgAE021Z.jpg
在某种程度上是畸形的,虽然code=200
,我在这里发布的代码不起作用,错误:
Corrupt JPEG data: premature end of data segment
java.io.FileNotFoundException: https://pbs.twimg.com/media/By_ui7QIgAE021Z.jpg
例外情况由指令openStream()
生成。
如何防止这种情况发生?如何检查图像有效性?
您的代码与输出不匹配。您的代码示例中没有任何内容能够输出“损坏的JPEG数据:数据段过早结束”。 – jarnbjo 2014-10-06 14:39:31