第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

Android設(shè)置Volley以從緩存中使用

Android設(shè)置Volley以從緩存中使用

我正在嘗試為服務(wù)器JSON響應(yīng)創(chuàng)建并使用緩存。例如:將JSON對(duì)象緩存到內(nèi)部存儲(chǔ)器中,并在沒(méi)有互聯(lián)網(wǎng)連接時(shí)使用它。在下面的示例代碼中,我找不到任何有關(guān)如何對(duì)其進(jìn)行緩存Volley并在服務(wù)器頭再次更新未到期時(shí)重新使用的文檔。像這樣:將過(guò)期設(shè)置為標(biāo)頭并使用緩存,并在過(guò)期后嘗試再次加載。我正在嘗試為此方法設(shè)置緩存機(jī)制:private void makeJsonArryReq() {    JsonArrayRequest req = new JsonArrayRequest(Const.URL_JSON_ARRAY,            new Response.Listener<JSONArray>() {                @Override                public void onResponse(JSONArray response) {                    msgResponse.setText(response.toString());                }            }, new Response.ErrorListener() {        @Override        public void onErrorResponse(VolleyError error) {        }    });    AppController.getInstance().addToRequestQueue(req,tag_json_arry);}緩存方法:public static Cache.Entry parseIgnoreCacheHeaders(NetworkResponse response) {    long now = System.currentTimeMillis();    Map<String, String> headers = response.headers;    long serverDate = 0;    String serverEtag = null;    String headerValue;    headerValue = headers.get("Date");    if (headerValue != null) {        serverDate = HttpHeaderParser.parseDateAsEpoch(headerValue);    }    serverEtag = headers.get("ETag");    final long cacheHitButRefreshed = 3 * 60 * 1000; // in 3 minutes cache will be hit, but also refreshed on background    final long cacheExpired = 24 * 60 * 60 * 1000; // in 24 hours this cache entry expires completely    final long softExpire = now + cacheHitButRefreshed;    final long ttl = now + cacheExpired;    Cache.Entry entry = new Cache.Entry();    entry.data = response.data;    entry.etag = serverEtag;    entry.softTtl = softExpire;    entry.ttl = ttl;    entry.serverDate = serverDate;    entry.responseHeaders = headers;    return entry;}
查看完整描述

2 回答

?
慕慕森

TA貢獻(xiàn)1856條經(jīng)驗(yàn) 獲得超17個(gè)贊

請(qǐng)注意,如果Web服務(wù)支持緩存輸出,則無(wú)需在CacheRequest下面使用,因?yàn)閂olley它將自動(dòng)緩存。


對(duì)于您的問(wèn)題,我在內(nèi)部使用了一些代碼parseCacheHeaders(并引用了@ oleksandr_yefremov的代碼)。我測(cè)試了以下代碼。當(dāng)然也可以使用JsonArrayRequest。希望對(duì)您有所幫助!


    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(0, mUrl, new Response.Listener<JSONObject>() {

        @Override

        public void onResponse(JSONObject response) {

            try {

                mTextView.setText(response.toString(5));

            } catch (JSONException e) {

                mTextView.setText(e.toString());

            }

        }

    }, new Response.ErrorListener() {

        @Override

        public void onErrorResponse(VolleyError error) {


        }

    }) {

        @Override

        protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {

            try {                    

                Cache.Entry cacheEntry = HttpHeaderParser.parseCacheHeaders(response);

                if (cacheEntry == null) {

                    cacheEntry = new Cache.Entry();

                }

                final long cacheHitButRefreshed = 3 * 60 * 1000; // in 3 minutes cache will be hit, but also refreshed on background

                final long cacheExpired = 24 * 60 * 60 * 1000; // in 24 hours this cache entry expires completely

                long now = System.currentTimeMillis();

                final long softExpire = now + cacheHitButRefreshed;

                final long ttl = now + cacheExpired;

                cacheEntry.data = response.data;

                cacheEntry.softTtl = softExpire;

                cacheEntry.ttl = ttl;

                String headerValue;

                headerValue = response.headers.get("Date");

                if (headerValue != null) {

                    cacheEntry.serverDate = HttpHeaderParser.parseDateAsEpoch(headerValue);

                }

                headerValue = response.headers.get("Last-Modified");

                if (headerValue != null) {

                    cacheEntry.lastModified = HttpHeaderParser.parseDateAsEpoch(headerValue);

                }

                cacheEntry.responseHeaders = response.headers;

                final String jsonString = new String(response.data,

                        HttpHeaderParser.parseCharset(response.headers));

                return Response.success(new JSONObject(jsonString), cacheEntry);

            } catch (UnsupportedEncodingException e) {

                return Response.error(new ParseError(e));

            } catch (JSONException e) {

                return Response.error(new ParseError(e));

            }

        }


        @Override

        protected void deliverResponse(JSONObject response) {

            super.deliverResponse(response);

        }


        @Override

        public void deliverError(VolleyError error) {

            super.deliverError(error);

        }


        @Override

        protected VolleyError parseNetworkError(VolleyError volleyError) {

            return super.parseNetworkError(volleyError);

        }

    };


    MySingleton.getInstance(this).addToRequestQueue(jsonObjectRequest);

更新:


如果需要基類(lèi),請(qǐng)參考以下代碼:


public class CacheRequest extends Request<NetworkResponse> {

    private final Response.Listener<NetworkResponse> mListener;

    private final Response.ErrorListener mErrorListener;


    public CacheRequest(int method, String url, Response.Listener<NetworkResponse> listener, Response.ErrorListener errorListener) {

        super(method, url, errorListener);

        this.mListener = listener;

        this.mErrorListener = errorListener;

    }



    @Override

    protected Response<NetworkResponse> parseNetworkResponse(NetworkResponse response) {

        Cache.Entry cacheEntry = HttpHeaderParser.parseCacheHeaders(response);

        if (cacheEntry == null) {

            cacheEntry = new Cache.Entry();

        }

        final long cacheHitButRefreshed = 3 * 60 * 1000; // in 3 minutes cache will be hit, but also refreshed on background

        final long cacheExpired = 24 * 60 * 60 * 1000; // in 24 hours this cache entry expires completely

        long now = System.currentTimeMillis();

        final long softExpire = now + cacheHitButRefreshed;

        final long ttl = now + cacheExpired;

        cacheEntry.data = response.data;

        cacheEntry.softTtl = softExpire;

        cacheEntry.ttl = ttl;

        String headerValue;

        headerValue = response.headers.get("Date");

        if (headerValue != null) {

            cacheEntry.serverDate = HttpHeaderParser.parseDateAsEpoch(headerValue);

        }

        headerValue = response.headers.get("Last-Modified");

        if (headerValue != null) {

            cacheEntry.lastModified = HttpHeaderParser.parseDateAsEpoch(headerValue);

        }

        cacheEntry.responseHeaders = response.headers;

        return Response.success(response, cacheEntry);

    }


    @Override

    protected void deliverResponse(NetworkResponse response) {

        mListener.onResponse(response);

    }


    @Override

    protected VolleyError parseNetworkError(VolleyError volleyError) {

        return super.parseNetworkError(volleyError);

    }


    @Override

    public void deliverError(VolleyError error) {

        mErrorListener.onErrorResponse(error);

    }

}

然后在MainActivity中,您可以像這樣調(diào)用


CacheRequest cacheRequest = new CacheRequest(0, mUrl, new Response.Listener<NetworkResponse>() {

        @Override

        public void onResponse(NetworkResponse response) {

            try {

                final String jsonString = new String(response.data,

                        HttpHeaderParser.parseCharset(response.headers));

                JSONObject jsonObject = new JSONObject(jsonString);

                mTextView.setText(jsonObject.toString(5));

            } catch (UnsupportedEncodingException | JSONException e) {

                e.printStackTrace();

            }

        }

    }, new Response.ErrorListener() {

        @Override

        public void onErrorResponse(VolleyError error) {

            mTextView.setText(error.toString());

        }

    });


    MySingleton.getInstance(this).addToRequestQueue(cacheRequest);

用全源代碼更新:


MainActivity.java:


package com.example.cachevolley;


import android.content.Context;

import android.os.Bundle;

import android.support.v7.app.AppCompatActivity;

import android.view.Menu;

import android.view.MenuItem;

import android.widget.TextView;

import android.widget.Toast;


import com.android.volley.Cache;

import com.android.volley.NetworkResponse;

import com.android.volley.Request;

import com.android.volley.RequestQueue;

import com.android.volley.Response;

import com.android.volley.VolleyError;

import com.android.volley.toolbox.HttpHeaderParser;

import com.android.volley.toolbox.Volley;


import org.json.JSONException;

import org.json.JSONObject;


import java.io.UnsupportedEncodingException;


public class MainActivity extends AppCompatActivity {


    private final Context mContext = this;


    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);


        final TextView textView = (TextView) findViewById(R.id.textView);


        RequestQueue queue = Volley.newRequestQueue(this);

        String url = "http://192.168.0.100/apitest";


        CacheRequest cacheRequest = new CacheRequest(0, url, new Response.Listener<NetworkResponse>() {

            @Override

            public void onResponse(NetworkResponse response) {

                try {

                    final String jsonString = new String(response.data,

                            HttpHeaderParser.parseCharset(response.headers));

                    JSONObject jsonObject = new JSONObject(jsonString);

                    textView.setText(jsonObject.toString(5));

                    Toast.makeText(mContext, "onResponse:\n\n" + jsonObject.toString(), Toast.LENGTH_SHORT).show();

                } catch (UnsupportedEncodingException | JSONException e) {

                    e.printStackTrace();

                }

            }

        }, new Response.ErrorListener() {

            @Override

            public void onErrorResponse(VolleyError error) {

                Toast.makeText(mContext, "onErrorResponse:\n\n" + error.toString(), Toast.LENGTH_SHORT).show();

            }

        });


        // Add the request to the RequestQueue.

        queue.add(cacheRequest);

    }


    @Override

    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.

        getMenuInflater().inflate(R.menu.menu_main, menu);

        return true;

    }


    @Override

    public boolean onOptionsItemSelected(MenuItem item) {

        // Handle action bar item clicks here. The action bar will

        // automatically handle clicks on the Home/Up button, so long

        // as you specify a parent activity in AndroidManifest.xml.

        int id = item.getItemId();


        //noinspection SimplifiableIfStatement

        if (id == R.id.action_settings) {

            return true;

        }


        return super.onOptionsItemSelected(item);

    }


    private class CacheRequest extends Request<NetworkResponse> {

        private final Response.Listener<NetworkResponse> mListener;

        private final Response.ErrorListener mErrorListener;


        public CacheRequest(int method, String url, Response.Listener<NetworkResponse> listener, Response.ErrorListener errorListener) {

            super(method, url, errorListener);

            this.mListener = listener;

            this.mErrorListener = errorListener;

        }



        @Override

        protected Response<NetworkResponse> parseNetworkResponse(NetworkResponse response) {

            Cache.Entry cacheEntry = HttpHeaderParser.parseCacheHeaders(response);

            if (cacheEntry == null) {

                cacheEntry = new Cache.Entry();

            }

            final long cacheHitButRefreshed = 3 * 60 * 1000; // in 3 minutes cache will be hit, but also refreshed on background

            final long cacheExpired = 24 * 60 * 60 * 1000; // in 24 hours this cache entry expires completely

            long now = System.currentTimeMillis();

            final long softExpire = now + cacheHitButRefreshed;

            final long ttl = now + cacheExpired;

            cacheEntry.data = response.data;

            cacheEntry.softTtl = softExpire;

            cacheEntry.ttl = ttl;

            String headerValue;

            headerValue = response.headers.get("Date");

            if (headerValue != null) {

                cacheEntry.serverDate = HttpHeaderParser.parseDateAsEpoch(headerValue);

            }

            headerValue = response.headers.get("Last-Modified");

            if (headerValue != null) {

                cacheEntry.lastModified = HttpHeaderParser.parseDateAsEpoch(headerValue);

            }

            cacheEntry.responseHeaders = response.headers;

            return Response.success(response, cacheEntry);

        }


        @Override

        protected void deliverResponse(NetworkResponse response) {

            mListener.onResponse(response);

        }


        @Override

        protected VolleyError parseNetworkError(VolleyError volleyError) {

            return super.parseNetworkError(volleyError);

        }


        @Override

        public void deliverError(VolleyError error) {

            mErrorListener.onErrorResponse(error);

        }

    }

}

清單文件:


<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.example.cachevolley" >


    <uses-permission android:name="android.permission.INTERNET" />


    <application

        android:allowBackup="true"

        android:icon="@mipmap/ic_launcher"

        android:label="@string/app_name"

        android:theme="@style/AppTheme" >

        <activity

            android:name=".MainActivity"

            android:label="@string/app_name" >

            <intent-filter>

                <action android:name="android.intent.action.MAIN" />


                <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>

        </activity>

    </application>


</manifest>

布局文件:


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:paddingBottom="@dimen/activity_vertical_margin"

    android:paddingLeft="@dimen/activity_horizontal_margin"

    android:paddingRight="@dimen/activity_horizontal_margin"

    android:paddingTop="@dimen/activity_vertical_margin"

    tools:context=".MainActivity">


    <TextView

        android:id="@+id/textView"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="@string/hello_world" />


</RelativeLayout>


查看完整回答
反對(duì) 回復(fù) 2019-11-14
?
精慕HU

TA貢獻(xiàn)1845條經(jīng)驗(yàn) 獲得超8個(gè)贊

如果響應(yīng)是使用字符串請(qǐng)求從服務(wù)器獲取的,則只需替換行


return Response.success(new JSONObject(jsonString), cacheEntry);

有了這個(gè)


return Response.success(new String(jsonString), cacheEntry);

在我的情況下有效。嘗試使用您自己的代碼。


查看完整回答
反對(duì) 回復(fù) 2019-11-14
  • 2 回答
  • 0 關(guān)注
  • 636 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)