【问题标题】:HttpURLConnection doesn't seem to be using cache on AndroidHttpURLConnection 似乎没有在 Android 上使用缓存
【发布时间】:2012-05-30 10:17:52
【问题描述】:

我最近将我的应用程序从使用 AndroidHTTPClient 切换到使用 HttpURLConnection。我正在尝试使 HttpURLConnection 的缓存功能正常工作,但没有成功。

这是我执行 Http 请求的代码

    URL url = new URL(currentURL);

    ResultAndUrl result = null;
    final HttpURLConnection httpUrlConnection = (HttpURLConnection) urll.openConnection();
    httpUrlConnection.setUseCaches(true);
    try {
        InputStream in = new BufferedInputStream(httpUrlConnection.getInputStream());
        result = new ResultAndUrl();
        result.result = convertStreamToString(in);
        result.url = currentURL;
    } catch (final Exception e) {
        try {
            Log.e("NETWORK", e.getMessage());
        } catch (Exception ee) {

        }
    } finally {
        try {
            httpUrlConnection.disconnect();
        } catch (Exception e) {
        }
    }

在我的应用程序类中我也有

public void enableHttpResponseCache() {
    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);
    } catch (Exception httpResponseCacheNotAvailable) {
        try{
            HttpResponseCache.install(httpCacheDir, httpCacheSize); // Library that implements HttpResponseCache for pre-ICS phones
        } catch(Exception e){
        }
    }
}

但是,即使对于 ICS 手机,也没有发生过缓存命中,而且缓存似乎根本没有做任何事情。如果我做错了什么或遗漏了什么,你能告诉我吗?

【问题讨论】:

  • 你为什么要更改实现包?如果您对 google 首选 UrlConnection 上的 google 示例不满意,请查看以下内容:code.google.com/p/httpclientandroidlibhc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/… 一般的想法是多线程实现是可扩展的/可靠的,并且通常由 android 开发人员使用。第一个链接中的客户端库维护良好,运行良好。那么,考虑线程池而不是缓存模式?
  • 如果发生缓存命中,您如何监控?查看服务器发送给您的标头。服务器可以禁止对某些请求进行缓存。

标签: android httpclient network-protocols httpresponse httpurlconnection


【解决方案1】:

http://pastebin.com/i60a90wv

以上链接中的“更新”方法是使用 http 线程池、https 和 http 帖子的示例代码。所以,除了建议上面评论中的链接外,我还在android中使用了它们。

更多代码(来自 HttpConnectionPost 类的可运行代码:

    public void run() {
//      Log.d(TAG, "run ENTRY instance"  +entry.toString());
        handler.sendMessage(Message.obtain(handler, HttpConnection.DID_START));
        HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(params, 40 * 1000);
        HttpConnectionParams.setSoTimeout(params, 20 * 1000);
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);

        httpClient = new DefaultHttpClient(MyConnectionManager.getInstance(), params);
//      HttpConnectionParams.setSoTimeout(httpClient.getParams(), 25000);
        httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
            public void process(
                    final HttpRequest request, 
                    final HttpContext context) throws HttpException, IOException {
                if (!request.containsHeader("Authorization")) {
                    request.addHeader("Authorization", "OAuth " +ClientCustomSSL.getInstance().getToken());
                }
            }

        }); 
        try {
            HttpResponse response = null;
            switch (method) {

            case POST:
                HttpPost httpPost = new HttpPost(url);
                if (data != null){
                    System.out.println(" post data not null ");
                    httpPost.setEntity(new StringEntity(data));
                }
                if (entry != null){
                    ContentProducer cp = new ContentProducer() {
                        public void writeTo(OutputStream outstream) throws IOException {

                             ExtensionProfile ep = new ExtensionProfile();
                             ep.addDeclarations(entry);
                             XmlWriter xmlWriter = new XmlWriter(new OutputStreamWriter(outstream, "UTF-8"));
                             entry.generate(xmlWriter, ep);
                             xmlWriter.flush();
                        }
                    };
                    httpPost.setEntity(new EntityTemplate(cp));
                }
                httpPost.addHeader("GData-Version", "2");
                httpPost.addHeader("X-HTTP-Method-Override", "PATCH");
                httpPost.addHeader("If-Match", "*");
                httpPost.addHeader("Content-Type", "application/xml");
                response = httpClient.execute(httpPost);

                break;
            }
            if (method < BITMAP)
                processEntity(response.getEntity());
        } catch (Exception e) {
            handler.sendMessage(Message.obtain(handler,
                    HttpConnection.DID_ERROR, e));
        }
        MyConnectionManager.getInstance().didComplete(this);
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-21
    • 2020-02-24
    • 2011-11-02
    • 1970-01-01
    • 2021-03-25
    • 1970-01-01
    相关资源
    最近更新 更多