【发布时间】:2016-03-19 18:42:50
【问题描述】:
我正在使用Android-Universal-Image-Loader 在我的Android 应用程序上通过HTTPS 从远程服务器加载图像。要访问图像,客户端应提供有效令牌,有时服务器可能会返回“过期 crsf 令牌”错误。为了处理此行为,应定义自定义 ImageDownloader。下面是在我的实现中应该被覆盖的方法的基本实现。
protected InputStream getStreamFromNetwork(String imageUri, Object extra) throws IOException {
HttpURLConnection conn = createConnection(imageUri, extra);
int redirectCount = 0;
while (conn.getResponseCode() / 100 == 3 && redirectCount < MAX_REDIRECT_COUNT) {
conn = createConnection(conn.getHeaderField("Location"), extra);
redirectCount++;
}
InputStream imageStream;
try {
imageStream = conn.getInputStream();
} catch (IOException e) {
// Read all data to allow reuse connection (http://bit.ly/1ad35PY)
IoUtils.readAndCloseStream(conn.getErrorStream());
throw e;
}
if (!shouldBeProcessed(conn)) {
IoUtils.closeSilently(imageStream);
throw new IOException("Image request failed with response code " + conn.getResponseCode());
}
return new ContentLengthInputStream(new BufferedInputStream(imageStream, BUFFER_SIZE), conn.getContentLength());
}
我想重写它以处理无效令牌错误。例如,如果服务器返回这样的错误,它应该被识别,应该重新生成令牌并重复请求。
我想出的唯一解决方案是这样的(缩短的代码):
imageStream = conn.getInputStream();
byte[] body = org.apache.commons.io.IOUtils.toByteArray(imageStream);
if (body.length < 300 // high probability to contain err message
&& isInvalidToken(body)) {
// handle error
}
return new ByteArrayInputStream(body);
考虑到我只将它用于最大 80kb 大小的缩略图,使用这种解决方案是否安全?还有其他解决方案吗?
【问题讨论】: