Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/186.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
需要Android中的HttpResponseCache示例吗_Android_Caching_Httpurlconnection_Httpresponsecache - Fatal编程技术网

需要Android中的HttpResponseCache示例吗

需要Android中的HttpResponseCache示例吗,android,caching,httpurlconnection,httpresponsecache,Android,Caching,Httpurlconnection,Httpresponsecache,您好,我正在尝试使用Android 4中引入的HttpResponseCache。文档中确实明确说明了如何安装缓存,但我完全不知道如何缓存从网络下载的图像。早些时候,我正在使用DiskLruCache缓存图像。有没有人能告诉我一些使用了HttpResponseCache的工作代码的例子 编辑:-有人能告诉我我做错了什么吗:- MainActivity.java public void onCreate(Bundle savedInstanceState) { super.onCreate

您好,我正在尝试使用Android 4中引入的HttpResponseCache。文档中确实明确说明了如何安装缓存,但我完全不知道如何缓存从网络下载的图像。早些时候,我正在使用DiskLruCache缓存图像。有没有人能告诉我一些使用了HttpResponseCache的工作代码的例子

编辑:-有人能告诉我我做错了什么吗:-

MainActivity.java
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final long httpCacheSize = 10 * 1024 * 1024; // 10 MiB
    final File httpCacheDir = new File(getCacheDir(), "http");
    try {
        Class.forName("android.net.http.HttpResponseCache")
            .getMethod("install", File.class, long.class)
            .invoke(null, httpCacheDir, httpCacheSize);
        Log.v(TAG,"cache set up");
    } catch (Exception httpResponseCacheNotAvailable) {
        Log.v(TAG, "android.net.http.HttpResponseCache not available, probably because we're running on a pre-ICS version of Android. Using com.integralblue.httpresponsecache.HttpHttpResponseCache.");
        try{
            com.integralblue.httpresponsecache.HttpResponseCache.install(httpCacheDir, httpCacheSize);
        }catch(Exception e){
            Log.v(TAG, "Failed to set up com.integralblue.httpresponsecache.HttpResponseCache");
        }
    }
    TheMainListFrag gf=(TheMainListFrag) getSupportFragmentManager().findFragmentByTag("thelistfrags");
    if(gf==null){
        gf=TheMainListFrag.newInstance();
        FragmentTransaction ft=getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.thelefty, gf,"thelistfrags");
        ft.commit();
    }
}
然后在主列表框架的加载程序中,我执行以下操作:-

public ArrayList<HashMap<String,String>> loadInBackground() {
    String datafromServer = null;
    ArrayList<HashMap<String,String>> al = new ArrayList<HashMap<String,String>>();
    try {
        String url = "someurl";
        HttpURLConnection urlConnection = (HttpURLConnection) new URL(url).openConnection();

        urlConnection.setRequestProperty("Accept", "application/json");
        InputStream is = new BufferedInputStream(urlConnection.getInputStream());
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        datafromServer=sb.toString();
        Log.v("fromthread",datafromServer);
        // etc 
                    //etc

    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        Log.v("fromthread", e.getClass() + "--" + e.getMessage());
    }

    return al;
}
public ArrayList loadInBackground(){
字符串datafromServer=null;
ArrayList al=新的ArrayList();
试一试{
字符串url=“someurl”;
HttpURLConnection urlConnection=(HttpURLConnection)新URL(URL).openConnection();
setRequestProperty(“接受”、“应用程序/json”);
InputStream is=new BufferedInputStream(urlConnection.getInputStream());
BufferedReader br=新的BufferedReader(新的InputStreamReader(is));
StringBuilder sb=新的StringBuilder();
字符串行=null;
而((line=br.readLine())!=null){
某人附加(行);
}
datafromServer=sb.toString();
Log.v(“fromthread”,datafromServer);
//等
//等
}捕获(格式错误){
//TODO自动生成的捕捉块
e、 printStackTrace();
}捕获(IOE异常){
//TODO自动生成的捕捉块
e、 printStackTrace();
}捕获(例外e){
Log.v(“fromthread”,e.getClass()+”--“+e.getMessage());
}
返回al;
}
当我连接到internet时,它工作正常,在上面命名的http目录和缓存目录中,我也可以看到文件。但当我没有连接到互联网时,数据拒绝加载

当我从网络中加载图像时,我看到名为.tmp的缓存文件,我认为它被称为DiskLruCache中的脏文件


如果您希望我提供任何其他信息,请告诉我。当您启用
HttpResponseCache
时,所有
HttpUrlConnection
查询都将被缓存。您不能使用它来缓存任意数据,因此我建议继续使用
DiskLruCache

部分强制缓存响应

有时,如果资源可用,您会希望显示它们 马上,但不是别的。这可以用于您的应用程序 在等待更新最新数据时可以显示某些内容 下载。要将请求限制为本地缓存的资源,请添加
仅当缓存时
指令:

这种技术在反应迟钝的情况下效果更好 总比没有反应好。要允许过时的缓存响应,请使用
max stale
指令的最大过期时间(秒):


在我的例子中,HttpResponseCache实际上并没有缓存任何东西。修复它的方法很简单:

connection.setUseCaches(true);
(在建立连接之前,必须在
HttpURLConnection
上调用此选项。)


对于更细粒度的控制,
max stale
可以用作。

HttpResponseCache仅适用于Http(s)URLConnection。你在用这些电话吗?这里有一个例子:是的,所有的事情都是这样做的。。我甚至在使用candrews库进行后移植。我看到json响应正在缓存,但无法缓存位图…为什么要使用反射?HttpResponseCache不适用于HttpClient。它适用于HttpUrlConnection。是的,它会自动缓存我的所有json等。。但是HttpResponseCache实现是否在内部不使用DiskLruCache。如果是这样的话,它不能用来缓存位图是的,我很抱歉-我不应该仅仅从内存中键入它。我的意思是,实际的
Bitmap
对象不存储在缓存中。但是,如果这是您的意思,那么应该缓存对图像的HTTP请求。更正了我的答案。请您详细说明一下-->“当您启用HttpResponseCache时,所有HttpUrlConnection查询都将被缓存”。如果您安装HttpResponseCache,它将缓存您使用HttpUrlConnection获得的所有响应。这意味着,当您再次发出相同的请求时,您可以立即获得缓存响应,甚至无需通过网络发送任何内容。我所说的图像是从HttpUrlConnection获得的,我的意思是它们是从网络下载的。这不是武断的数据谢谢Jesse。。这就成功了。。。但是,当我从网上下载图像时,它们会以.tmp扩展名显示。当我直接使用DiskLruCache时,这似乎不会发生。使用HttpResponseCache会使用堆内存还是本机内存?+1。在我的例子中,只需在请求中设置
max stale
,就可以修复从HttpResponseCache.Hmm,实际上
connection.setUseCaches(true)中没有读取任何内容的情况对我来说已经足够了。
int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale
connection.addRequestProperty("Cache-Control", "max-stale=" + maxStale);
connection.setUseCaches(true);