【发布时间】:2016-01-04 16:00:05
【问题描述】:
我曾经通过计算响应的哈希来避免解析服务器响应,如果它没有没有改变:: p>
public class HttpClient {
protected OkHttpClient mClient = new OkHttpClient();
public String get(final URL url, final String[] responseHash)
throws IOException {
HttpURLConnection connection = new OkUrlFactory(mClient).open(url);
InputStream inputStream = null;
MessageDigest messageDigest = null;
try {
messageDigest = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
assert messageDigest != null;
try {
// Read the response.
inputStream = connection.getInputStream();
byte[] response = readFully(inputStream);
final byte[] digest = messageDigest.digest(response);
responseHash[0] = Base64.encodeToString(digest, Base64.DEFAULT);
return new String(response, Util.UTF_8);
} finally {
if (inputStream != null) {
inputStream.close();
}
}
}
private byte[] readFully(InputStream in) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
for (int count; (count = in.read(buffer)) != -1; ) {
out.write(buffer, 0, count);
}
return out.toByteArray();
}
}
这是响应头:
HTTP/1.1 200 OK
Server: Apache/2.4.10 (Linux/SUSE)
X-Powered-By: PHP/5.4.20
X-UA-Compatible: IE=edge
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Expires: Thu, 08 Oct 2015 16:15:09 +0000
X-Frame-Options: SAMEORIGIN
Content-Type: application/json; charset=utf-8
Transfer-Encoding: chunked
Date: Wed, 07 Oct 2015 16:15:09 GMT
X-Varnish: 505284843
Age: 0
Via: 1.1 varnish
Connection: keep-alive
现在我切换到Retrofit 我想知道避免解析相同响应的优雅方法是什么? 拦截器是要走的路吗?我不负责服务器后端,也不能修改它。
【问题讨论】:
-
If-Modified-Since?当然你需要逻辑后端 -
或
E-tag标头,当然,如果您的后端已实现此功能。 w3.org/Protocols/rfc2616/rfc2616-sec14.html14.9 -
@JJD 您是否愿意重新下载数据然后检查内容,而不是在下载前检查数据是否已更改?那不是效率低吗?
-
@axierjhtjz 不。如果我可以避免使用给定的后端多次下载数据,我宁愿不这样做。但是,当这不可能时,我想避免解析。
标签: http-headers response retrofit okhttp http-caching