本文介绍了需要的Htt presponseCache在Android的一个例子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我想使用的Htt的presponseCache在安卓4.文档介绍了不说清楚有关如何安装的缓存,但我在如何缓存图片完全丧失从net.Earlier我下载是使用DiskLruCache对其进行缓存。会有人指出我对工作code一些例子,其中的Htt presponseCache已被使用。

编辑: - 谁能告诉我什么,我做错了什么: -

  MainActivity.java
公共无效的onCreate(包savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_main);
    最终长httpCacheSize = 10 * 1024 * 1024; // 10 MIB
    最终文件httpCacheDir =新的文件(getCacheDir(),HTTP);
    尝试 {
        的Class.forName(android.net.http.Htt presponseCache)
            .getMethod(安装,File.class,long.class)
            .invoke(NULL,httpCacheDir,httpCacheSize);
        Log.v(TAG,缓存设置);
    }赶上(例外HTT presponseCacheNotAvailable){
        Log.v(TAG,android.net.http.Htt presponseCache不可用,可能是因为我们正在运行在Android上的pre-ICS版本。使用com.integralblue.htt presponsecache。 HttpHtt presponseCache)。
        尝试{
            com.integralblue.htt presponsecache.Htt presponseCache.install(httpCacheDir,httpCacheSize);
        }赶上(例外五){
            Log.v(TAG,无法设置com.integralblue.htt presponsecache.Htt presponseCache);
        }
    }
    TheMainListFrag GF =(TheMainListFrag)getSupportFragmentManager()findFragmentByTag(thelistfrags)。
    如果(GF == NULL){
        GF = TheMainListFrag.newInstance();
        FragmentTransaction英尺= getSupportFragmentManager()的BeginTransaction()。
        ft.replace(R.id.thelefty,广发,thelistfrags);
        ft.commit();
    }
}
 

然后在TheMainListFrag的装载机,我做了如下: -

 公开的ArrayList< HashMap的<字符串,字符串>> loadInBackground(){
    字符串datafromServer = NULL;
    ArrayList的< HashMap的<字符串,字符串>>人=新的ArrayList< HashMap的<字符串,字符串>>();
    尝试 {
        字符串URL =someurl;
        HttpURLConnection的的URLConnection =(HttpURLConnection类)新的网址(URL).openConnection();

        urlConnection.setRequestProperty(接受,应用/ JSON);
        InputStream的是=新的BufferedInputStream(urlConnection.getInputStream());
        的BufferedReader BR =新的BufferedReader(新InputStreamReader的(是));
        StringBuilder的SB =新的StringBuilder();
        串线= NULL;
        而((行= br.readLine())!= NULL){
            sb.append(线);
        }
        datafromServer = sb.toString();
        Log.v(fromthread,datafromServer);
        // 等等
                    //等等

    }赶上(MalformedURLException异常E){
        // TODO自动生成的catch块
        e.printStackTrace();
    }赶上(IOException异常E){
        // TODO自动生成的catch块
        e.printStackTrace();
    }赶上(例外五){
        Log.v(fromthread,e.getClass()+ - + e.getMessage());
    }

    返回人;
}
 

当我连接到互联网,它工作正常,并在目录中的HTTP-上述命名的缓存目录,我可以看到文件了。但是,当我没有连接到互联网,数据拒绝加载。

当我从网上载入图像,我看到命名为.tmp文件的缓存文件,我相信被称为肮脏按DiskLruCache。

请让我知道,如果有任何其他的信息,你要我提供

解决方案

这部分的强制缓存响应上的:

 尝试{
    connection.addRequestProperty(缓存控制,只有-IF-缓存);
    InputStream的缓存= connection.getInputStream();
    //资源被缓存!展示下
}赶上(FileNotFoundException异常E){
    //资源没有缓存
}
 
  INT maxStale = 60 * 60 * 24 * 28; //容忍4周陈旧
connection.addRequestProperty(缓存控制,MAX-陈旧=+ maxStale);
 

Hi I am trying to use the HttpResponseCache introduced in Android 4.The docs do talk clearly about how to install the cache but I am at a complete loss on how to cache Images downloaded from the net.Earlier I was using the DiskLruCache to cache them. Would anyone point me towards some examples of working code where HttpResponseCache has been used..

Edit:- Can someone tell me what I am doing wrong here:-

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();
    }
}

Then in the loader of TheMainListFrag, I do the below:-

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;
}

When i am connected to internet, it works fine, and in the directory http-the cache directory named above, i can see the files too. But when I am not connected to the internet, the data refuses to load.

When i load images from the net, i see the cache files named as .tmp , which i believe are termed as dirty as per DiskLruCache.

Please let me know if there is any other info that you want me to provide

解决方案

From the section Force a Cache Response on the HttpResponseCache documentation:

try {
    connection.addRequestProperty("Cache-Control", "only-if-cached");
    InputStream cached = connection.getInputStream();
    // the resource was cached! show it
} catch (FileNotFoundException e) {
    // the resource was not cached
}
int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale
connection.addRequestProperty("Cache-Control", "max-stale=" + maxStale);

这篇关于需要的Htt presponseCache在Android的一个例子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 13:49