bvk*_*256 9 java android java-io
我正在使用Android-Universal-Image-LoaderHTTPS在我的Android应用程序上从远程服务器加载图像.要访问映像,客户端应提供有效的令牌,有时服务器可能会返回"过期的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());
}
Run Code Online (Sandbox Code Playgroud)
我想重写它来处理无效的令牌错误.例如,如果服务器返回此错误,则应该识别它,应该重新生成令牌并重复请求.
我提出的唯一解决方案就是这样(缩短代码):
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);
Run Code Online (Sandbox Code Playgroud)
使用这种解决方案是否安全,考虑到我只使用最大80kb尺寸的缩略图?还有其他解决方案吗?
您的解决方案是安全的,尽管如果您创建ImageDownloaderInputStream实现InputStream并包装原始InputStream. 您可以从底层输入流中预加载(缓冲)一些块来检测内容是否有效。
您应该重写的唯一方法是read()。
如果内容有效,则可以将缓冲区内容提供给调用者,当缓冲区为空时,直接从底层流式传输InputStream。
如果内容无效,只需读取另一个流,或返回零长度流。
public class ImageDownloaderInputStream extends InputStream {
private byte[] buffer = null;
private int bufLen = 0;
private int bufIndex = 0;
private boolean isContentValid;
private InputStream wrapped;
public ImageDownloaderInputStream (InputStream wrapped) {
this.wrapped = wrapped;
}
@Override
public ind read() {
if(buffer == null) {
// check content and fill buffer
this.isContentValid = checkContent();
}
if (this.isContentValid) {
if(bufIndex < bufLen) {
return buffer[bufIndex++] & 0xFF;
} else {
return wrapped.read();
}
} else {
// error handling: zero-length stream
return -1;
}
}
private boolean checkContent() {
// fill the buffer
this.buffer = new byte[1024];
this.bufLen = wrapped.read(this.buffer);
// read more if not enough
// check the content
return true;
// return false;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
987 次 |
| 最近记录: |